开发者

Bash , append line at the end of each file

I have files in a dir. I need to append a new line开发者_开发百科 and the file name at the end of each file.


This should do:

for f in *; do echo >> $f; echo $f >> $f; done
  • First echo a new-line, then echo the filename.

  • The >> says "append at the end of the file".


Edit: aioobe's answer has been updated to show the -e flag that I didn't see when I first answered this. Thus I'm now just showing an example which includes a directory and how to eliminate the directory name:

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

If you want the directory name, take out the shortname=${fn/#*\//} line and replace $shortname with $fn in the echo.


Let xargs do the looping:

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

or

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

or

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

or

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


Another method using ex (or vim) :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜