Home > other >  Sed to match special characters and add special characters
Sed to match special characters and add special characters

Time:10-16

I trying to do 3 operations on a file using sed.

  1. remove {master} if its above specific string "string@string>string|string"
  2. remove date "Oct 14 22:55:58" if its below specific string "string@string>string|string"
  3. add a string " after matching ""

"test@test-re0> show version | display xml" is just an example and it can vary and also can have spaces or no spaces after special characters '>', '|'. But format is same i.e. string@string>string|string

Example:

{master}
test@test-re0> show version | display xml
Oct 14 22:55:58 
<rpc-reply>
</rpc-reply>

test@test-re0> show hardware|display xml
Jan 04 01:55:58 
<rpc-reply>
</rpc-reply>

Expected result

test@test-re0> show version | display xml
<rpc-reply">
</rpc-reply>
<ENDSTRING>

test@test-re0> show hardware|display xml
<rpc-reply>
</rpc-reply>
<ENDSTRING>
1.sed "/^{master}$/d" input.txt - This matches and deletes {master}
2.[a-zA-Z]{3}\s*\d\d\s\d\d:\d\d:\d\d - regex matches date but doesn't work in sed
3.sed "/^</rpc-reply>/a <ENDSTRING>" input.txt - Doesnot work

I want to combine all 3 operations into single command and save it to separate file.

CodePudding user response:

You may use this sed script to do this all in a single sed command:

cat cmd.sed

/^\{master}/ {
   N
   s/. \n([^@] @[^|] \|.)/\1/
}
/^[^@] @[^|] \|./ {
   N
   s/(. )\n[A-Za-z]{3} [0-9]{2} ([0-9]{2}:){2}[0-9]{2}/\1/
}
/^<\/rpc-reply>/a \
<ENDSTRING>

Use it as:

sed -E -f cmd.sed file

test@test-re0> show version | display xml22:55:58
<rpc-reply>
</rpc-reply>
<ENDSTRING>

test@test-re0> show hardware|display xml01:55:58
<rpc-reply>
</rpc-reply>
<ENDSTRING>

CodePudding user response:

This might work for you (GNU sed):

sed -E ':a;N
        s/^\{master\}\n(\S @\S >\s \S[^\n]*\|[^\n]*)/\1/;ta
        s/^(\S @\S >\s \S[^\n]*\|[^\n]*)\n... .. ..:..:..[^\n]*/\1/;ta
        /\n<\/rpc-reply>$/{P;s/.*\n(.*)/\1\n<ENDSTRING>/};P;D' file

Open up a two line window throughout the file by appending the next line.

If the first line of the window is {master}, delete that line and append the next line i.e. repeat from the start.

If the second line of the window contains a date, delete that line and append the next line i.e. repeat from the start.

If the second line of the window contains </rpc-reply>, print the first line of the window, delete the first line of the window and append the required string.

Print/delete the first line of the window and repeat.

  • Related