0

I want to remove files in directory except a specific file and print a message if files remove.

find . ! -name 'name' -type f -exec echo 'removed files:' rm -v -f {} +

When I run this command it prints:

removed files: rm -v -f ./aaavl ./aaavlpo

I want to print putput like:

removed files:
./aaavl
./aaavlpo

How should I do this?

F.M
  • 463
  • 2
  • 7
  • 20

2 Answers2

1

Just use find in a Bash loop to modify the output.

Given:

$ ls -1
file 1
file 2
file 3
file 4
file 5

You can still loop and negate with find as desired. Just use Bash to delete and report:

$ find . ! -name *3 -type f | while read fn; do echo "removing: $fn";     rm "$fn"; done
removing: ./file 1
removing: ./file 2
removing: ./file 5
removing: ./file 4

$ ls -1
file 3

That loop will work for filenames with spaces OTHER THAN \n.

If there is a possibility of file names with \n in them, use xargs with a NUL delimiter:

$ find . ! -name *3 -type f -print0 | xargs -0 -n 1 -I% bash -c ' echo "%" ; rm "%" ;' 

And add the header echo "removed files:" above the loop or xargs pipe as desired.

dawg
  • 98,345
  • 23
  • 131
  • 206
0

maybe it's not a better way, but ...

1 - Save the file names in .txt: find -name 'name' -type f -exec echo >> test.txt {} \;

2 after saving the files, executing the deletion of the files find. ! -name 'name' -type f -exec rm -f {} +

Kleudy Silva
  • 26
  • 1
  • 3