Home > Mobile >  sed command replace muti line with reg
sed command replace muti line with reg

Time:06-22

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

CodePudding user response:

If your file contains only the two lines you showed, then this might help with GNU sed:

sed -i 'N; s/decrypt_aes(\n *//; s/)//' file

From man sed:

N: Append the next line of input into the pattern space.

CodePudding user response:

This might work for you (GNU sed):

sed 'N;s/decrypt_aes.*\(".*"\).*/\1/;P;D' file

Append the following line and if the combined lines matches decrpty_aes followed by "...", replace the match by the string "...".

N.B. If no match is found, each line will be printed as is.

CodePudding user response:

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"
  • Related