How to print a series of columns to CSV in AWK?
With awk
I can print any column to CSV, for example this will print the 10th column to file.csv
.
awk -F, '{ print $10 }' file.csv
If I need to print columns 5-10 including the comma, I only know like this:
awk -F, '{ print $5","$6","$7","$8","$9","$10 }' file.csv
This method is not very good if I want to print many columns. Is there an easier syntax for printing a range of columns to CSV in awk
?
source to share
The standard way to do this in awk is to use a for loop:
awk -v s=5 -v e=10 'BEGIN{FS=OFS=","}{for (i=s; i<=e; ++i) printf "%s%s", $i, (i<e?OFS:ORS)}' file
However, if your delimiter is simple (as in your example), you can use cut
:
cut -d, -f5-10 file
Perl deserves a mention (with help -a
to enable unattended install mode):
perl -F, -lane '$"=","; print "@F[4..9]"' file
source to share
You can use a loop in awk to print columns from 5 to 10:
awk -F, '{ for (i=5; i<=10; i++) print $i }' file.csv
Be aware that when used, print
it will print each column on a new line. If you want to print them on one line with OFS
, then use:
awk -F, -v OFS=, '{ for (i=5; i<=10; i++) printf("%s%s", $i, OFS) }' file.csv
source to share
With GNU awk for gensub ():
$ cat file
a,b,c,d,e,f,g,h,i,j,k,l,m
$
$ awk -v s=5 -v n=6 '{ print gensub("(([^,]+,){"s-1"})(([^,]+,){"n-1"}[^,]+).*","\\3","") }' file
e,f,g,h,i,j
s
is the starting position, and n
is the number of fields to print from this point. Or, if you prefer to specify start and end:
$ awk -v s=5 -v e=10 '{ print gensub("(([^,]+,){"s-1"})(([^,]+,){"e-s"}[^,]+).*","\\3","") }' file
e,f,g,h,i,j
Note that this will only work with single-character field delimiters as it relies on the ability to dump FS into a character class.
source to share