sed command replace muti line with reg

I got a text like this:

TOKEN = decrypt_aes(
    "189272123124aqephkiz3")

And I want to change it into:

TOKEN = "189272123124aqephkiz3"

How can I make this?
I can do this when its in a single line with following command:enter code here`

sed -i "s/decrypt_aes(\(.*\))/\1/g"

But I don`t no how to do when its in multi line

>Solution :

You can use

sed -i '/.*decrypt_aes($/{N;s/^\([^=]*=\).*\(".*"\))$/\1 \2/}' file

Details:

  • /.*decrypt_aes($/ – matches a line that ends with decrypt_aes( substring, and if it matches, the block that follows is executed
  • N – append a newline and the next line to the pattern space
  • s/^\([^=]*=\).*\(".*"\))$/\1 \2/ – replaces
    • ^\([^=]*=\).*\(".*"\))$ – start of string in the pattern space (^), any zero or more chars other than = and then a = are captured into Group 1 (\1), then any text (.*), then a "..." substring (captured into Group 2 (\2)) and then a ) at the end of string
    • \1 \2 is the replacement pattern, which is Group 1 value + space + Group 2 value.

See the online demo:

#!/bin/bash
s='TOKEN = decrypt_aes(
    "189272123124aqephkiz3")'

sed '/.*decrypt_aes($/{N;s/^\([^=]*=\).*\(".*"\))$/\1 \2/}' <<< "$s"

Output:

TOKEN = "189272123124aqephkiz3"

Leave a Reply