bash method to remove last 4 columns from csv file

后端 未结 8 1322
后悔当初
后悔当初 2021-01-01 21:48

Is there a way to use bash to remove the last four columns for some input CSV file? The last four columns can have fields that vary in length from line to line so it is not

8条回答
  •  轮回少年
    2021-01-01 22:34

    awk one-liner:

    awk -F, '{for(i=0;++i<=NF-5;)printf $i", ";print $(NF-4)}'  file.csv
    

    the advantage of using awk over cut is, you don't have to count how many columns do you have, and how many columns you want to keep. Since what you want is removing last 4 columns.

    see the test:

    kent$  seq 40|xargs -n10|sed 's/ /, /g'           
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    11, 12, 13, 14, 15, 16, 17, 18, 19, 20
    21, 22, 23, 24, 25, 26, 27, 28, 29, 30
    31, 32, 33, 34, 35, 36, 37, 38, 39, 40
    
    kent$  seq 40|xargs -n10|sed 's/ /, /g' |awk -F, '{for(i=0;++i<=NF-5;)printf $i", ";print $(NF-4)}'
    1,  2,  3,  4,  5,  6
    11,  12,  13,  14,  15,  16
    21,  22,  23,  24,  25,  26
    31,  32,  33,  34,  35,  36
    

提交回复
热议问题