-1

I have large number of csv files saved within a folder. I would like to, only, delete the csv files that contains one row, how can I do that?

faujong
  • 115

1 Answers1

2

The number of lines in a file called MyFile.csv can be had with wc -l <MyFile.csv. This number may be compared with 1 and the file removed using

if [ "$( wc -l <MyFile.csv )" -eq 1 ]; then
    rm -i MyFile.csv
fi

The $(...) is a command substitution that will be replaced by the output of the command within. The -i option to rm makes the utility ask for confirmation before deleting anything.

To generalize this to all CSV files in the current directory:

for filename in ./*.csv; do
    if [ "$( wc -l <"$filename" )" -eq 1 ]; then
        rm -i "$filename"
    fi
done

To generalize further to all CSV files in the current directory or anywhere below in any subdirectory:

find . -type f -name '*.csv' -exec sh -c '
    for pathname do
        if [ "$( wc -l <"$pathname" )" -eq 1 ]; then
            rm -i "$pathname"
        fi
    done' {} +

Always back up your data, especially if you intend to test run scripted file deletions.

Kusalananda
  • 333,661