2

In bash, how to delete all the files starting with file using file* but keep file.txt?

I tried this

shopt -s extglob

rm file* !(file.txt)

But the file.txt is still deleted.

PS: I only need to delete the files starting with file, not all the files. E.g. I want a file named food.txt still kept.

lanselibai
  • 1,203
  • 2
  • 19
  • 35

3 Answers3

6

You need to use the "negative" pattern match as the file extension:

$ ls file.*
file.csv  file.json  file.txt  file.xml

$ ls file.!(txt)
file.csv  file.json  file.xml
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

The find command can help you here. For example:

find . -maxdepth 1 -not -name 'file.*' -not -name '*.txt' -delete
James Patrick
  • 32
  • 1
  • 7
1

find approach:

find . -maxdepth 1 -type f -name 'file*' ! -name "file.txt" -delete
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105