繁体   English   中英

Bash,在每个文件的末尾附加一行

[英]Bash , append line at the end of each file

我有文件在一个目录。 我需要在每个文件的末尾附加一个新行和文件名。

这应该做:

for f in *; do echo >> $f; echo $f >> $f; done
  • 首先回显一个新行,然后回显文件名。

  • >>说“附加在文件的末尾”。

编辑:aioobe的答案已经更新,以显示我第一次回答这个问题时没有看到的-e标志。 因此,我现在只是展示一个包含目录以及如何消除目录名称的示例:

#!/bin/bash
for fn in dir/* 
do
  shortname=${fn/#*\//}
  echo -e "\n$shortname" >> $fn
done

如果你想要目录名,请取出shortname=${fn/#*\\//}行,并在echo中用$ fn替换$ shortname。

xargs进行循环:

# recursive, includes directory name
find -type f -print0 | xargs -0 -I% bash -c 'echo -e "\n%" >> %'

要么

# non-recursive, doesn't include directory name
find -maxdepth 1 -type f -exec basename {} \; | xargs -I% bash -c 'echo -e "\n%" >> %'

要么

# non-recursive, doesn't include directory name
find -maxdepth 1 -type f -printf "%f\0" | xargs -0 -I% bash -c 'echo -e "\n%" >> %'

要么

# recursive, doesn't include directory name
find -type f -print0 | xargs -0 -I% bash -c 'f=%; echo -e "\n${f##*/}" >> %'

使用ex (或vim)的另一种方法:

ex -c 'args **/*' -c 'set hidden' -c 'argdo $put =bufname(".")' -c 'wqa'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM