4

I have a directory that I is filled by another user, and I'm tasked with maintaining it. I want to delete all its content except a 2 files with a specific name. Is it possible with rm or should I do this:

cp aaa/a ./a && cp aaa/b ./b && rm -rf aaa/* && mv ./a aaa/a && mv ./b aaa/b

where aaa is the directory, a,b are the files I want to keep, and there are (at least, there may be) other files/directories in there.

Is there a better (and shorter) way?

1 Answers1

9

With bash extended globs, given

$ tree aaa
aaa
├── a
├── b
├── c
├── d
├── e
└── subdir

then

rm -rf aaa/!(a|b)

leaves

$ tree aaa
aaa
├── a
└── b

0 directories, 2 files
steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • Cool! is there a way to use this also in sh? I'm getting there -sh: !: event not found – CIsForCookies Jul 08 '18 at 12:50
  • 2
    Based on the error message, you're actually using it in bash but with the extended glob feature disabled - in a script, you may need to add shopt -s extglob at the top. But no, AFAIK you can't do the same in POSIX sh / dash – steeldriver Jul 08 '18 at 12:57