Adding header into multiple text files [duplicate]

2020-04-17 03:18发布

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' *

1条回答
狗以群分
2楼-- · 2020-04-17 03:56

Option 1: Works pretty much any version of Unix

tmp=$(mktemp)   # Create a temporary file
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15

header="This is the header line to be inserted"

for file in "$@"
do
    {
    echo "$header"
    cat $file
    } > $tmp
    mv $tmp $file
done

rm -f $tmp
trap 0

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:

tmp=${TMPDIR:-/tmp}/ins.$$

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.

header="This is the line to be inserted"

for file in "$@"
do
    sed -i -e "1i\
$header" $file
done

This inserts the value of $header before the first line of each file. You could write the edit script into a file and use sed -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 or ex to edit the file. You could use Perl or Python or awk to do the processing.

查看更多
登录 后发表回答