Pectus Excavatum
Pectus Excavatum

Reputation: 3783

shell adding multiple lines within the middle of a file

I am just wondering what is the best way to add multiple lines within a file. I.e. I want to replace a tag within a file i.e. /#tag

with multiple lines, say 3

echo "line 1"
echo "line 2"
echo "line 3"

I know I can read each line of the file and if I encounter the tag could pipe the new lines to the file, however, due to the size of the file, that takes way too long.

I am sure there must be a better way?

Upvotes: 1

Views: 294

Answers (1)

Graeme
Graeme

Reputation: 3041

Just use sed:

sed -i 's:/#tag:line 1\nline 2\nline 3:' file

The s command is simply 'substitute', usually the separator would be a / but since this is in the tag we can use : instead. See http://www.grymoire.com/unix/sed.html if you have never used sed before. The /#tag can be a regular expression, just as with grep.

Upvotes: 3

Related Questions