I have a directory containing lot of files in different formats. I would like to know how I can delete all files with specific format (Lets say *.dat) except a few files in a same format (e.g. A.dat and B.dat). Please advise!
Asked
Active
Viewed 403 times
-1
-
1What did you try? and how did you fail? – Inian Jan 20 '17 at 08:34
-
2http://unix.stackexchange.com/a/214410/13792 – choroba Jan 20 '17 at 08:35
1 Answers
1
I'd write a little script (as a command-line one-liner it is slightly too big):
#!/bin/sh
for f in *.dat; do
case $f in
(A.dat|B.dat)
;; # do nothing
(*)
rm -- "$f";; # remove the file
esac
done
As an alternative, you could use an interactive rm -i *.dat
which asks you for each file if it should be removed. Answer y
for the files you no longer need, and n
for A.dat
and B.dat
.
Modern shells like zsh and bash also offer powerful globbing features for your problem. I suggest you read their manual pages, which will help you become a proficient shell guru.

Jens
- 69,818
- 15
- 125
- 179
-
Thanks for the reply, that works to me but I'm wondering if there is any one-line script that can do the same preferably !! – Soheil Jan 20 '17 at 10:54