How can I delete numbered files in a given range?
Assuming you know or can guess the end of the range, you could use brace expansions:
rm a_{000750..000850}
The above will delete the 101 files between a_000750 and a_000850 inclusive (and complain about filenames that refer to non-existing files). If you have too many files for that, use find
:
find . -name 'a_*' | while read file; do
[ "${file#./a_}" -gt 000749 ] && rm -v "$file"
done
Here, the find
simply lists all files matching a_*
. The list is passed to a while
loop where each file name is read into the variable $file
. Then, using bash's string manipulation features, if the numerical part (find prints files as ./file
, so ${file#./a_}
prints the number only) is 000750
or greater, the file is deleted. The -v
is just there so you can see what files were removed.
Note that the above assumes sane file names. If your names can have spaces, newlines or other weird characters, use this instead:
find . -name 'a_*' -print0 | while IFS= read -rd '' file; do
[ "${file#./a_}" -gt 000749 ] && rm -v "$file"
done
You could do something like this:
find . -regextype posix-extended -iregex './a_[0-9]{6}' -execdir bash -c '[[ ${1##./a_} > 000750 ]] && echo $1' "removing: " {} \;
Or:
find . -regextype posix-extended -iregex './a_[0-9]{6}' | sort | sed '0,/000750/d' | xargs echo
The first method assumes a fixed prefix, strips it off and checks the value.
The second method assumes a fixed-length suffix (and a common fixed prefix) and relies on that fact; and that, while 201
comes before 31
in lexicographically, it doesn't before 031
.
Test this out with the echo
command, and once you're sure it lists the correct files, use rm
instead.