Issue
I trying to do 3 operations on a file using sed.
- remove {master} if its above specific string "string@string>string|string"
- remove date "Oct 14 22:55:58" if its below specific string "string@string>string|string"
- 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.
Solution
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>
Answered By - anubhava Answer Checked By - Clifford M. (WPSolving Volunteer)