Possible Duplicate:
Sed/Awk to search and replace/insert text in files
I would like to know how to add one "header" line into multiple text files contained in one directory. Bash command line would be great!
Thx.
EDIT
I found my needs in here: http://perldoc.perl.org/index-faq.html enjoy! Here is my answer:
perl -pi -e 'print "**MyHeaderText**\n" if $. == 1' *
Option 1: Works pretty much any version of Unix
This creates a temporary file securely and makes sure it gets removed under a reasonable collection of signals (HUP, INT, QUIT, PIPE and TERM). The main loop then copies the header string and the file to the temporary, and moves the temporary over the original, removes any leftover file (in case something went wrong) and cancel the cleanup so the shell can exit cleanly.
If your original file had multiple (hard) links, or if it was a symlink, you lose these special properties. To fix that, you have to use
cp $tmp $file
, and then you have to remove the file in$tmp
too.If you don't have the
mktemp
comand, you can use:to generate a name. It is more easily predictable than the name from
mktemp
and less secure, especially if you're running as root. There might also be wisdom in using the current directory as$TMPDIR
if you have multiple file systems.Option 2: GNU sed
If you have GNU
sed
and you don't have symlinks or hard links to deal with, then you can use its-i
option to do an in-place alter.This inserts the value of
$header
before the first line of each file. You could write the edit script into a file and usesed -i -f sed.script $file
to avoid awkward indentation in the loop.Option 3: Other tools
There are many other possible techniques. For example, you could use
ed
orex
to edit the file. You could use Perl or Python orawk
to do the processing.