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

标签 linux find echo delete-file

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

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/

相关文章:

sql-server - SQL Server 能否在 SCO SantaCruz Operations SO (Linux) 上运行?

linux - 状态错误 : no such file or directory while building Docker from a custom image with Docker build command

asp.net - 使用 Find 方法在通用列表中查找对象

powershell - PowerShell 的正则表达式无法与/n(换行符)一起使用

java - 通过POST发送参数到php文件并读取php文件的echo

echo - 软件回声消除器如何工作?

linux - Vagrant 的麻烦 - "404 - Not Found"

linux - Bash循环比较文件

linux - 如何选择目录中的所有文件并运行命令

PHP 使用 echo over print 的实际优势