Issue
Let us say I have the following text:
name is test1 and age is test2 end
name is test3 and age is test4 end
name is test5 and age is test6 end
name is test7 and age is test8 end
I am grepping for test1, test2, ... as follows:
-bash$ grep -o -P "is .*? and|is .*? end" test
is test1 and
is test2 end
is test3 and
is test4 end
is test5 and
is test6 end
is test7 and
is test8 end
Is there a way I can prepend some text to the matched pattern? I am looking for an output like this:
STRING1:is test1 and
STRING2:is test2 end
STRING1:is test3 and
STRING2:is test4 end
STRING1:is test5 and
STRING2:is test6 end
STRING1:is test7 and
STRING2:is test8 end
Solution
You could use sed
in a pipeline (admittedly it's not very clean):
$ grep -o -P "is .*? and|is .*? end" test | sed '/and$/s/^/STRING1:/; /end$/s/^/STRING2:/'
STRING1:is test1 and
STRING2:is test2 end
STRING1:is test3 and
STRING2:is test4 end
STRING1:is test5 and
STRING2:is test6 end
STRING1:is test7 and
STRING2:is test8 end
The /.nd$/
before each substitution restricts the substitution to acting on lines that match that regex.
Answered By - huon Answer Checked By - Marie Seifert (WPSolving Admin)