Jack15
Jack15

Reputation: 19

Extract/cut strings the matching lines

I am trying to extract/cut some part from the beginning of matching lines in my file. Remove all before matching [SUCCESS] & [FAILURE] lines. content is similar as below

[1] 10:32:54 [SUCCESS] host123
hyujhbjbhjbjk cbcjd
yuiiiik,,................
[2] 10:32:54 [FAILURE] host123
jbjk cbcjd
yuiiiik,,................
[3] 10:32:54 [SUCCESS] host12356
jhbjbhjbjk cbcjd
yuiiiik,,................

Need expected as below output. with one space/blank line

[SUCCESS] host123
hyujhbjbhjbjk cbcjd
yuiiiik,,................

[FAILURE] host123
jbjk cbcjd
yuiiiik,,................

[SUCCESS] host12356
jhbjbhjbjk cbcjd
yuiiiik,,................

I am trying below sed command , but not helping

sed -n 's/^.*[SUCCESS]/[SUCCESS]/p'
sed -n 's/^.*[FAILURE]/[FAILURE]/p'

Upvotes: 0

Views: 472

Answers (2)

Aaron
Aaron

Reputation: 24822

I think you should :

  • escape the [ in your search pattern
  • stop using the -n flag and rely on automatic printing

If you don't mind a leading empty line I would use the following, which leverages capturing group and backreference :

sed -E 's/.*(\[SUCCESS\]|\[FAILURE\])/\n\1/' file

or

sed -E 's/.*\[(SUCCESS|FAILURE)\]/\n[\1]/' file

You can try it here.

Upvotes: 1

Dominique
Dominique

Reputation: 17575

Looks to me that you try to remove the [n] <date> part of the files, which can be expressed using following regular expression:

grep -o "\[[0-9]\] [0-9][0-9]\:[0-9][0-9]\:[0-9][0-9] " *

As you see, using grep -o you can show only that part of the line.
Using grep -v you can exclude the line, containing that expression.

I was hoping that grep -ov would combine both into showing the entire lines, removing the expression, but this seems not be the case.

Can somebody give the last push and edit my answer accordingly?

Upvotes: 0

Related Questions