I want to insert some text in the middle of a file. The text to insert would be after a specific line, say, "<begin>". I don't know the line number, nor do I know the number of lines in the text to insert. I only know that after the line that reads "<begin>" I need to insert the content of another file.

I just don't know how to use awk to do something like this.

Thanks :-)

link|improve this question

feedback

2 Answers

up vote 1 down vote accepted

Perl is awk's bigger brother.

perl -p -i -e 'print "some text\n" if /<begin>/' filename

If you have multiple <begin>s then it will need amending.

EDIT: Oh you wanted to insert a file

perl -MFile::Slurp -p -i -e 'print read_file("file2") if /<begin>/' filename

(tested OK but you might need cpan File::Slurp first.)

link|improve this answer
feedback
/<begin>/{
    insert_file("before_file.html")
    print $0
    insert_file("after_file.html")
    next
}
{
    print $0
}

where you will have to write the insert_file function which might look something like

function insert_file(file) {
    while (getline line <file)
        print line
    close(file)
}

Note that this exact version doesn't seem to be working as expected on my Mac when before_file and after_file are the same...I'm only getting the only the first copy. It probably has something to do with failing to close the file. I shall investigate. Yes, it is necessary to close the file, and that should be done in general for good practice.


Also, I think this might be even easier in sed...

For inserting the file after the key line

sed '/<begin>/r after_file.html' input_file

Inseting the file before is a little more complicated,

 sed -n -e '/^function/r before_file.html' -e 'x' -e 'p' input_file

so you could use a script like

/^function/r before_file.html
x
p

with

sed -n -f script input_file
link|improve this answer
With this sed script, you're going to have an issue with the last line, which is left unprinted in the hold space. You could fix by adding a final -e '${g;p}', or by making sure your input has an extra \n at the end. – dubiousjim Apr 19 at 11:01
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.