How to Delete Numbered Files in a Given Range Using Command Line

bashcommand linescripts

I have folderA that has some files with a number sequence starting with a_000000. What I want to do is to delete files starting from a specific number: let's say a_000750 till the end of files in this folderA. Could anyone please advise how to do this using shell script?

Best Answer

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
Related Question