Delete row which has more than X columns in a csv

前端 未结 2 1147
误落风尘
误落风尘 2021-01-23 01:07

I need to delete all the rows in a csv file which have more than a certain number of columns.

This happens because sometimes the code, which generates the csv file, ski

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-23 01:23

    Try the following (do not omit to replace your file path and your max column):

    #! /bin/bash
    
    filepath=test.csv
    max_columns=3
    
    for line in $(cat $filepath);
    do
        count=$(echo "$line" | grep -o "," | wc -l)
        if [ $(($count + 1)) -le $max_columns ]
                then
                echo $line
        fi
    done
    

    Copy this in a .sh file (cropper.sh for example), make it executable chmod +x cropper.sh and run ./cropper.sh).

    This will output only the valid lines. You can then catch the result in a file this way:

    ./cropper.sh > result.txt

提交回复
热议问题