我想删除目录中除特定文件以外的文件,并在文件删除时打印一条消息。
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:"
。
关于linux - 删除目录中的文件并打印删除的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519638/