ddn
ddn

Reputation: 429

How to delete an unpredictable number of files if they are named with a higher number than X

I have a number of files in directories which are numbered as file_1.txt, file_2.txt, file_3.txt and so on. I would like to delete any files with a number above, for example, 5 (so deleting file_6.txt, file_7.txt and so on). I do not know how many of these files there are in each directory, or if there even are that many files. These numbers do not correspond to how recently the files were last accessed.

On prior occasions, when files were created in order and I have known how many I need to delete, I have used this command, but I can't figure out how to adapt it to the unknown:

ls -t | tail -n5 | xargs --no-run-if-empty rm

Upvotes: 1

Views: 144

Answers (1)

Moldova
Moldova

Reputation: 1651

Since you tagged your question as shell, not bash, I tried to avoid bash-isms and use lowest common denominator sh syntax. I believe this does what you're asking:

#!/bin/sh

for file in *
do
    num=`echo $file | sed 's/file_\([0-9][0-9]*\)\.txt/\1/'`
    if [ "$num" -gt 5 ]
    then
      echo Removing $file
      # Uncomment when confident results are correct
      # rm $file
    fi
done 

I believe the non-Gnu sed on many systems does not support the + operator, thus the need for [0-9][0-9]* instead to ensure at least one digit.

Upvotes: 2

Related Questions