bash - 一行命令清空终端中的多个文本文件

标签 bash shell

您将如何使用单个命令清空终端中的多个文本文件?

我的想法是,您可以按照这些思路使用一些东西...:

find /var/log/apache2/*log -exec `echo > '{}'` \;

我知道创建一个 shell 脚本很简单:

echo "#!/bin/sh\n\necho \"\" > \"$1\"" > /usr/local/bin/empty && chmod +x /usr/local/bin/empty

...

find /var/log/apache2/*.log -exec empty {} \;

但是否可以在不以类似方式创建自己的脚本的情况下做到这一点?

最佳答案

#!/bin/bash

for file in /var/log/apache2/*.log; do
  : > "$file"
done

或者单行版本

for file in /var/log/apache2/*.log; do : > "$file"; done

如果你需要递归到子目录,那么你可以使用以下两个选项:

bash 4.X

shopt -s globstar; for file in /var/log/apache2/**.log; do : > "$file"; done

正统

find /var/log/apache2 -type f -name "*.log" -exec sh -c 'for f; do : > "$f"; done' _ {} +

关于bash - 一行命令清空终端中的多个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8685576/

相关文章:

linux - 按进程数和最活跃用户排名最高的用户

shell - 如何在非交互模式下配置 pam-auth-update?

php - 运行 php shell_exec 而不向浏览器返回结果?

bash - 如何删除包含特定字符串的所有行,但仅当后面的字符是 CJK 字符时?

bash - 在 MAC OSX 中比较 Bash 中的两个日期

c - 从 C 应用程序运行 shell 脚本

linux - bash 猫多个文件

linux - apt-get install 只显示最后一行

regex - shell/bash : use sed/awk to get string between special characters

arrays - Bash 脚本 Leet 文本转换器 : How to get array to recognize spaces