Bash, add a line at the end of each file

I have files in a directory. I need to add a new line and a file name at the end of each file.

+5
source share
4 answers

This should do:

for f in *; do echo >> $f; echo $f >> $f; done
  • First repeat the new line, then the echo file name.

  • >> says add to end of file.

+7
source

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

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

If you need a directory name, remove the line shortname=${fn/#*\//}and replace $ shortname with $ fn in the echo.

0
source

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##*/}" >> %'
0

ex ( vim):

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

All Articles