tags:

views:

36

answers:

2

I'm trying extract the nth + 1 and nth + 3 columns from a file.

This is what tried, which is a useful pseudo code:

for i in {1..100} ; do awk -F "," " { printf \"%3d, %12.3f, %12.3f\\n\", \$1, \$($i+1), \$($i+3) } " All_Runs.csv > Run-$i.csv

which, obviously doesn't work (but it seemed reasonable to hope).

How can I do this?

A: 

Wait a minute, it does work if I type the command correctly ...

for i in {1..2} ; do awk -F "," " { printf \"%3d %12.3f %12.3f\\n\", \$1, \$($i+1), \$($i+3) } " All_Runs.csv ; done

Was missing the ; done. Doh!

Jamie
+1  A: 

You can avoid some hairy quoting and escaping by using awk to do the incrementing:

awk -F "," 'BEGIN { i = j = 1 } { i++; j+=3; printf "%3d, %12.3f, %12.3f\n", $1, $i, $j > Run-$i.csv }' All_Runs.csv 

Or by using awk's variable-passing feature:

for i in {1..100}; do awk -F "," -v i=$i '{ i++; j=i+2; printf "%3d, %12.3f, %12.3f\n", $1, $i, $j }' All_Runs.csv > Run-$i.csv; done

(both untested)

Dennis Williamson
Looks like the second one needs `i=i` → `i=$i`?
Chris Johnsen
@Chris: Thanks.
Dennis Williamson