Replace a line with multiple lines in a file

I want to replace one line in a file with several lines, for example

I want to replace a specific function call say foo(1,2)

from

 if (a > 1) { foo(1,2) } else { bar(1,2) } 

How can I do this in bash?

+6
source share
3 answers

This sed s command was created for:

 shopt -s extglob ORIG="foo(1,2)" REP="if (a > 1) { foo(1,2) } else { bar(1,2) }" REP="${REP//+( )/\\n}" sed "s/$ORIG/$REP/g" inputfile > outputfile 

Please note that the lines REP="${REP//\+( )/\\n}" necessary only if you want to define REP in the formatted format that I did on the second line. It might be easier if you just used \n and \t in REP to start.

Edit in response to an OP question

To change the source file without creating a new file, use the sed --in-place flag, for example:

 sed --in-place "s/$ORIG/$REP/g" inputfile 

Please be careful with the --in-place flag. Make backups before starting, because all changes will be permanent.

+6
source
 ORIGINAL="foo(1,2)" REPLACEMENT="if (a > 1) { foo(1,2) } else { bar(1,2) }" while read line; do if [ "$line" = "$ORIGINAL" ]; then echo "$REPLACEMENT" else echo "$line" fi done < /path/to/your/file > /path/to/output/file 
+1
source

This might work for you:

 cat <<\! | > a > foo(1,2) > b > foo(1,2) > c > ! > sed '/foo(1,2)/c\ > if (a > 1) {\ > foo(1,2)\ > } else {\ > bar(1,2)\ > }' a if (a > 1) { foo(1,2) } else { bar(1,2) } b if (a > 1) { foo(1,2) } else { bar(1,2) } c 
0
source

Source: https://habr.com/ru/post/915624/


All Articles