bashunixseded

Replace a line with multiple lines in a file


I want to replace a single line in a file with multiple lines, e.g., I want to replace a particular function call, say,

foo(1,2)

with

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

How can I do it in bash?


Solution

  • This is what the sed s command was built 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
    

    Note that the REP="${REP//\+( )/\\n}" lines are only needed if you want to define the REP in the formatted way that I did on line two. It might be simpler if you just used \n and \t in REP to begin with.

    Edit: Note! You need to escape ' and \ as well in your REP if you have them.

    Edit in response to the OP's question

    To change your original file without creating a new file, use sed's --in-place flag, like so:

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

    Please be careful with the --in-place flag. Make backups before you run it because all changes will be permanent.