1

I want to add a line with some content, say

This is a test 23

to all the files inside a directory. The content will be added as first line to the file. There are about 800 files in the directory. Is there an easier way to do this than writing some perl command or bash script?

6 Answers 6

0

Your going to have to use some code, but not much:

for I in `ls *.txt`
do
  mv ${I} ${I}.tmp
  cat ${I}.tmp | awk 'BEGIN {print "Test to add"} {print $0}' > ${I}
  rm ${I}.tmp
done

The reason for renaming the file first is that reading and writing to the same file at the same time can cause problems (at least it does for me).

You'll want to add a test in there to make sure the new file is created properly before deleting the old one.

3

The answer is at Stack Overflow:

https://stackoverflow.com/questions/520742/prepend-to-multiple-files-in-bash-osx-terminal

1

If you are just appending to the end of the file you can do it easily with something like the bash code listed below.

for i in *.txt
do
echo "This is a test 23" >> $i
done
1
  • 1
    I am trying to add to the begining of the file rather than appending. how can i change the above for that need?
    – josh
    Aug 4, 2009 at 23:48
0

Nope, simple bash script is the way I'd tackle it.

More specifically, I'd write a bash script to call sed to do the actual file editing, but the principle stands. You're not going to be able to iterate through a list of files without some shell code.

0

perl is the easiest way. for example:

perl -n -i -e 'local $/ ; print "This is a test 23\n$_";' *.txt
0

sed is quicker than perl and awk and more elegant, I think:

for i in *.txt; do
    sed -i '1i\
    text to add
    ' $i
done

You must log in to answer this question.