1

I have files:

a.txt
b.txt
e.txt
c.c
d.o

I want to delete ONLY .txt files excluding e.txt, so the files which will remain at the end are:

e.txt
c.c
d.o
  • How to delete executable files which are also present in the same directory adding to above scenario – Abhishek Gupta Sep 20 '16 at 12:30
2

given:

cpetro01@<work_laptop> ~/Notes/test
$ ls
a.jpg  a.txt  b.mov  b.txt  c.jpg  c.mov

do:

$ find ./ -name "*.txt" -not -name "e.txt"
./a.txt
./b.txt

thus:

cpetro01@<work_laptop> ~/Notes/test
$ ls
a.jpg  a.txt  b.mov  b.txt  c.jpg  c.mov  e.txt

cpetro01@<work_laptop> ~/Notes/test
$ find ./ -name "*.txt" -not -name "e.txt" -exec rm {} \;

cpetro01@<work_laptop> ~/Notes/test
$ ls
a.jpg  b.mov  c.jpg  c.mov  e.txt

Like that?

  • How to delete executable files which are also present in the same directory adding to above scenario – Abhishek Gupta Sep 20 '16 at 12:31
  • Read the "find" man page. It's got all sorts of ways to find files. – Petro Sep 21 '16 at 15:50
0

Two ways:

  • Using GLOBIGNORE variable to indicate the file name(s) that would be ignored while globbing:

    GLOBIGNORE=e.txt
    rm -- *.txt
    unset GLOBIGNORE
    
  • Setting extglob option, and using extended globbing to match all .txt files except e.txt:

    shopt -s extglob
    rm -- !(e).txt
    shopt -u extglob
    
  • Yes correct, i have a small add on. How to delete executable files also which are present in the same directory adding to above scenario. – Abhishek Gupta Sep 20 '16 at 4:05
0

This will list all .txt files except for e.txt:

ls -1 *.txt | grep -v '^e.txt$'

You can then do command substitution to tell rm to delete those files:

rm $(ls -1 *.txt | grep -v '^e.txt$')
  • Yes correct, i have a small add on. How to delete executable files also which are present in the same directory adding to above scenario. – Abhishek Gupta Sep 20 '16 at 4:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.