Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a word with multiple lines using sed?

I'm working on a bash-script that has to prepare an E-Mail for being sent to a user.

It aggregates some data, which ends up being multiple lines of stuff. For the example stored in $DATA.

Now, after a bit of stfw I found a few things like sed -ei "s/_data_/${DATA}/g" mail.tpl and also sed replace with variable with multiple lines. None of them work.

Now the question is, how do I get sed to replace something with multiple lines of text?

(Alternatives to sed are also welcome!)

like image 466
Cobra_Fast Avatar asked Apr 11 '12 13:04

Cobra_Fast


People also ask

How do you replace a word using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


2 Answers

You can do this with AWK using variable substitution. We can set a variable in AWK using -v, and then use AWK's gsub function to substitute all occurrences of a regular expression with that variable.

For example, if the file test has the following contents ...

foo bar blah _data_and_data_ foo _data_ foobar _data_ again 

... and the Bash variable $DATA is ...

1 2 3 4 5 

... then awk -v r=$DATA '{gsub(/_data_/,r)}1' test replaces all occurrences of the regular expression _data_ in the file test with the contents of $DATA, resulting in the following:

foo bar blah 1 2 3 4 5and1 2 3 4 5 foo 1 2 3 4 5 foobar 1 2 3 4 5 again 
like image 181
Kent Avatar answered Oct 05 '22 17:10

Kent


I would suggest simply replacing sed with perl command like this:

perl -i.bak -pe 's/_data_/$ENV{"DATA"}/g' mail.tpl  
like image 23
anubhava Avatar answered Oct 05 '22 16:10

anubhava