Replace a word with multiple lines using sed?

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

Leave a Comment