Bash,在每个文件末尾追加行

问题描述:

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

这应该这样做:

for f in *; do echo >> $f; echo $f >> $f; done 
  • 首先呼应了新线,然后回显文件名。

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

+0

这并不在文件名前添加请求换行符。 – MForster 2010-11-04 21:49:19

+0

更新了答案。 – aioobe 2010-11-04 21:51:21

+0

如果文件名包含\? 'printf'\ n%s \ n'“$ f”' – ephemient 2010-11-05 01:31:39

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

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

如果你想要的目录名,取出shortname=${fn/#*\//}线和替换$短名称与$回声FN 。

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'