Monday, April 29, 2024
48
rated 0 times [  48] [ 0]  / answers: 1 / hits: 57024  / 1 Year ago, sun, january 15, 2023, 10:00:52

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?


More From » command-line

 Answers
4

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 -r 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

[#23052] Tuesday, January 17, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sipwing

Total Points: 245
Total Questions: 100
Total Answers: 118

Location: Aland Islands
Member since Thu, Oct 22, 2020
4 Years ago
sipwing questions
Sun, May 29, 22, 22:00, 2 Years ago
Fri, Jun 24, 22, 08:46, 2 Years ago
Fri, Dec 23, 22, 00:04, 1 Year ago
;