Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 0 down vote accepted

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

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

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.

share|improve this answer

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
echo "This is a test 23" >> $i
share|improve this answer
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 '09 at 23:48

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.

share|improve this answer

perl is the easiest way. for example:

perl -n -i -e 'local $/ ; print "This is a test 23\n$_";' *.txt
share|improve this answer

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

for i in *.txt; do
    sed -i '1i\
    text to add
    ' $i
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.