I am trying to make my bash script a function with Bash input parameter but AWK's syntax is causing a problem. Original AWK code
http://stackoverflow.com/a/19602188/54964
awk -F "\"*,\"*" '{print $2}' textfile.csv
Pseudocode with Bash parameter $1
file=$(awk -v colN="$1" -F "\"*,\"*" '{print $"${colN}"}' "${input}")
# http://stackoverflow.com/a/19602188/54964
# http://stackoverflow.com/a/19075707/54964
The problem is the part print $"${colN}"
.
Current output fails to catch the second column and takes the whole line etc
-0.21,-0.245
-0.205,-0.22
Having only print $colN
is not correct, since it takes then always the first column regardless of the value in $1
.
Example of the use case where I call it by bash code.bash 2
; or complete script here which works if you do not hard-code which column to choose (1/2) in all two-column CSV files for the joined result of second columns
#!/bin/bash
ids=(101 118 201)
dir="/home/masi/Documents/CSV/"
index=0
for id in "${ids[@]}";
do
input=$(echo "${dir}P${id}C1.csv")
# take second column of the file here
file=$(awk -v colN="$1" -F "\"*,\"*" '{print $colN}' "${input}") # http://stackoverflow.com/a/19602188/54964 # http://stackoverflow.com/a/19075707/54964
Ecgs[${index}]="${file}"
index=$index+1
done
Inputs multicolumn 1.csv 2.csv 3.csv
-0.21,-0.245
-0.205,-0.22
Wanted output
101,118,201
-0.245,-0.245,-0.245
-0.22,-0.22,-0.22
OS: Debian 8.5
Bash 4.30
colN
, and yes, to refer to the number of column, you use a $ – magor Nov 03 '16 at 16:34$colN
? – magor Nov 03 '16 at 16:36paste
is a better solution, a solution was provided earlier to you – magor Nov 03 '16 at 16:51>>
, not>
. If it's a working script, you might post it on http://codereview.stackexchange.com. – Wildcard Nov 03 '16 at 16:56paste -d, /home/masi/Documents/CSV/P{101,118,201}C1.csv | awk -F, -v OFS=, '{print $2, $4, $6}'
but if there is ever more than two fields in the input files that won't work as expected. – Wildcard Nov 03 '16 at 17:12