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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is what the sed
scommand was built for:Note that the
REP="${REP//\+( )/\\n}"lines are only needed if you want to define theREPin the formatted way that I did on line two. It might be simpler if you just used\nand\tinREPto 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-placeflag, like so:Please be careful with the
--in-placeflag. Make backups before you run it because all changes will be permanent.