AWK – How to Print Range of Columns

awkcsvtext formattingtext processing

if I have a csv file in the following format:

column1,column2,column3,column4,column5,column6,column7,column8

and I want awk to only print columns 2 till 7 I would use:

awk -F',' '{print $2 "," $3 "," $4 "," $5 "," $6 "," $7}' file.csv

and get:

column2,column3,column4,column5,column6,column7

is there a way to concatenate the columns 2-7 to simplify the command. As I'm thinking of a file with quite a bit more columns, my awk command would get horribly long.

Best Answer

$ awk -v b=2 -v e=7 'BEGIN{FS=OFS=","} {for (i=b;i<=e;i++) printf "%s%s", $i, (i<e ? OFS : ORS)}' file
column2,column3,column4,column5,column6,column7

b=beginning field number, e=end field number. If you need to handle CSVs with quoted fields, embedded commas, newlines, etc. then see https://stackoverflow.com/q/45420535/1745001.

Related Question