Extract specific columns from delimited file using Awk

后端 未结 8 1913
-上瘾入骨i
-上瘾入骨i 2020-11-28 05:44

Sorry if this is too basic. I have a csv file where the columns have a header row (v1, v2, etc.). I understand that to extract columns 1 and 2, I have to do: awk -F \

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 06:34

    If Perl is an option:

    perl -F, -lane 'print join ",",@F[0,1,2,3,4,5,6,7,8,9,19,20,21,22,23,24,29,32]'

    -a autosplits line into @F fields array. Indices start at 0 (not 1 as in awk)
    -F, field separator is ,

    If your CSV file contains commas within quotes, fully fledged CSV parsers such as Perl's Text::CSV_XS are purpose-built to handle that kind of weirdness.

    perl -MText::CSV_XS -lne 'BEGIN{$csv=Text::CSV_XS->new()} if($csv->parse($_)){@f=$csv->fields();print (join ",",@f[0,1,2,3,4,5,6,7,8,9,19,20,21,22,23,24,29,32])}'

    I provided more explanation within my answer here: parse csv file using gawk

提交回复
热议问题