0

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

1 Answers1

1

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

Cyrus
  • 77,979
  • 13
  • 71
  • 125
  • While that would probably work for exactly the sample input strings provided, in general you'd have to escape the `.` and any other regexp metachars that could occur in `search_variable` and add anchors for the search and escape `&` and any other backreferences like `\1` in `new_variable` for that ro be robust. See [is-it-possible-to-escape-regex-metacharacters-reliably-with-sed](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed). – Ed Morton Mar 19 '22 at 00:43
  • @EdMorton: yes, you would have to replace `${search_variable}` with `${search_variable//./\\.}` to escape all possible dots. – Cyrus Mar 19 '22 at 00:49
  • @Curus that would only escape `.`, it wouldn't help for any other metachars (or `/`s) that might be present and it wouldn't help for partial matches like if `fooDlog4j2.formatMsgNoLookupsbar` existed in the input. It also wouldn't help for `&` and other chars in `new_variable`. Like I said, though, it'd probably work for the 2 strings in the question depending on the rest of the contents of the input file it's run on. – Ed Morton Mar 19 '22 at 00:51
  • when i am trying to run the same command again on the same file, it is commenting the existing line, and appending duplicate line. How can i avoid this? other than putting one more if loop to see if the string is already present or not. – Praveen Kumar Mar 19 '22 at 01:26
  • @PraveenKumar: Insert `^[^#]` before first `.*` to match only rows not starting with `#`. – Cyrus Mar 19 '22 at 01:53