Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

6 Answers

up vote 0 down vote accepted

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.

share|improve this answer
add comment

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
share|improve this answer
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 '09 at 23:48
add comment

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
add comment

perl is the easiest way. for example:

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

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
share|improve this answer
add comment

Your Answer

 
discard

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