0

As a part of my bash routine I am trying to add IF condition which should remove all csv filles contained pattern "filt" in their names:

# this is a folder contained all subfolders
results=./results
# looping all directories located in the $results
for d in "${results}"/*/; do
  if [ -f "${d}"/*filt*.csv ]; check if csv file is present within dir $d
   rm "${d}"/*filt*.csv # remove this csv file
  fi
done

Although a version without condition find and removes the csv properly:

rm "${d}"/*filt*.csv

While executing my example with IF gives the following error:

line 27: [: too many arguments

where the line 27 corresponds to the IF condition. How it could be fixed?

can I use something like without any IF statement?

# find all CSV filles matching pattern within the "${d}"
find "${d}" -type f -iname *filt*.csv* -delete
  • You can't do `-f` on glob patterns. – 0stone0 Apr 20 '21 at 16:39
  • 1
    Anyway, using [tag:find] this can be simplified to something like: `find ./results -type f -iname '*filt*.csv* -delete` – 0stone0 Apr 20 '21 at 16:40
  • 1
    Otherwise, take a look at [Test whether a glob has any matches in bash](https://stackoverflow.com/questions/2937407/test-whether-a-glob-has-any-matches-in-bash). – 0stone0 Apr 20 '21 at 16:41
  • what would be the difference between this and just rm how was shown in my working example? –  Apr 20 '21 at 16:41

1 Answers1

3

You could use shopt -s nullglob and then skip the test and use rm -f "$d"/*filt*.csv directly. The nullglob option makes sure that the glob not matching anything expands to the empty string, and -f would silence rm.

You could also skip the outer loop and simplify everything to

shopt -s nullglob
rm -f results/*filt*.csv

This could fail if the glob matches so many files that the maximum line length is exceeded. In that case, you're better off with find:

find results -name '*filt*.csv' -exec rm {} +

or, with GNU find:

find results -name '*filt*.csv' -delete

If there are subdirectories you want to skip, use -maxdepth 1. If there are directories matching the pattern, use -type f.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116