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?
Asked
Active
Viewed 1,685 times
-1
faujong
- 115
1 Answers
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
wc -lto select file then remove it. – Prvt_Yadav Sep 20 '18 at 14:33