I am trying to comment a line in a file using search pattern, and then insert new line next to it.
search_variable=Dlog4j2.formatMsgNoLookups
new_variable="wrapper.java.additional.47=-Dlog4j2.formatMsg=false"
cat testfile.txt
wrapper.java.additional.47=-Dlog4j2.formatMsgNoLookups=true
This one works, but trying to use variable to comment the line and
sed -i '/Dlog4j2.formatMsgNoLookups/s/^/#/g' testfile.txt
output:
#wrapper.java.additional.47=-Dlog4j2.formatMsgNoLookups=true
Desired output
cat testfile.txt
#wrapper.java.additional.47=-Dlog4j2.formatMsgNoLookups=true
wrapper.java.additional.47=-Dlog4j2.formatMsg=false
CodePudding user response:
With GNU sed
:
search_variable="Dlog4j2.formatMsgNoLookups"
new_variable="wrapper.java.additional.47=-Dlog4j2.formatMsg=false"
sed -i "s/.*${search_variable}.*/#&\n${new_variable}/" testfile.txt
Output to testfile.txt:
#wrapper.java.additional.47=-Dlog4j2.formatMsgNoLookups=true
wrapper.java.additional.47=-Dlog4j2.formatMsg=false
For the meaning of &
see using sed with ampersand (&).
The curly brackets can also be omitted in this case.
This can also be helpful: Difference between single and double quotes in bash