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
1
  • How to delete executable files which are also present in the same directory adding to above scenario Sep 20, 2016 at 12:30

3 Answers 3

3

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?

2
  • How to delete executable files which are also present in the same directory adding to above scenario Sep 20, 2016 at 12:31
  • Read the "find" man page. It's got all sorts of ways to find files.
    – Petro
    Sep 21, 2016 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
    
1
  • 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. Sep 20, 2016 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$')
1
  • 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. Sep 20, 2016 at 4:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .