Nourless
Nourless

Reputation: 854

How can I delete files with odd names from directories?

Given files 0..9.txt in directories foo and bar, how can I 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.

Upvotes: 0

Views: 490

Answers (2)

William Pursell
William Pursell

Reputation: 212198

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 {} +

Upvotes: 7

Christian Fritz
Christian Fritz

Reputation: 21354

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

Upvotes: -2

Related Questions