删除目录中的文件并打印删除的文件名

remove files in directory and print the deleted files name

我想删除目录中除特定文件以外的文件,并在文件删除时打印一条消息。

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

当我 运行 这个命令时它打印:

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

我想像这样打印putput:

removed files:
./aaavl
./aaavlpo

我应该怎么做?

只需在 Bash 循环中使用 find 即可修改输出。

给定:

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

您仍然可以根据需要循环并使用 find 取反。就用Bash删除举报:

$ 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

该循环适用于包含 \n 以外空格的文件名。

如果文件名中可能包含 \n,请使用带有 NUL 分隔符的 xargs

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

并根据需要在循环或 xargs 管道上方添加 header echo "removed files:"

也许这不是更好的方法,但是...

1 - 以 .txt 格式保存文件名: find -name 'name' -type f -exec echo >> test.txt {} \;

2 保存文件后,执行文件的删除 寻找。 ! -name 'name' -type f -exec rm -f {} +