Home > Back-end >  How to delete files with odd names from directories?
How to delete files with odd names from directories?

Time:10-05

Given files 0..9.txt in directories foo and bar how to remove those which are odd? I've come up with

find . -regextype egrep -regex ".*[0-9].txt"  | while read file; do    [ `expr match "$file" '[0-9]'`% 2 -eq 0 ] && rm -v "$file" ; done

But it doesn't work. I do not understand how properly set up finding the number in the full filename and check its parity.

CodePudding user response:

find . -name '*[13579].txt' -delete

If your find doesn't support -delete, use:

find . -name '*[13579].txt' -exec rm {} \;

or

find . -name '*[13579].txt' -exec rm {}  

CodePudding user response:

find . -regextype egrep -regex ".*[0-9].txt" |
  while read file; do \
    n=$(basename $file .txt); \
    if [[ $((n % 2)) == 1 ]]; then \
      rm -v $file; \
    fi; \
  done
  • Related