2

It was an old problem. I knew how to delete files and exclude some, like this:

rm `find ~/temporary/Test\ 1 -mindepth 1 -maxdepth 1|grep -v 'A'`

but the problem is the folder 'Test 1' containing a space in name, the result of find was

/home/owner/temporary/Test 1/B

It makes rm error, how can I fix it?

Kevin Panko
  • 7,466
John
  • 23

2 Answers2

2

This solution works even with spaces but requires some typing:

find -mindepth 1 -maxdepth 1 ! -name "peter" ! -name "paul & mary" -exec rm {} \+

Or with newer find versions (findutils >= 4.2.3):

find -mindepth 1 -maxdepth 1 ! -name "peter" ! -name "paul & mary" -delete
scai
  • 1,100
1

Here is my take:

$ mkdir -p temp\ 1/sub\ 1
$ touch temp\ 1/{one,two,three} temp\ 1/sub\ 1/{one,two,three}
$ tree temp\ 1/
temp\ 1/
├── one
├── sub\ 1
│   ├── one
│   ├── three
│   └── two
├── three
└── two

1 directory, 6 files
$ find temp\ 1/ -maxdepth 1 -mindepth 1 -type f ! -regex '.*/.*o.*' -exec rm -v {} \;
removed ‘temp 1/three’

So the key concepts here are:

  1. The -regex filter with negation (! before option) and the pattern that is applied to the whole path of the found file.
  2. The -exec command that has the {} token replaced with properly quoted path. Remember to add the \; to mark the end of the command line.
Rajish
  • 650