perl command: Prepend a line of text only at the first occurrence
By Emma Valentine •
I have this input file:
text1
match
text2
match
text3And I have this command:
perl -lpe 'print "prepend_me" if /^match$/' text.txtAnd its output is:
text1
prepend_me
match
text2
prepend_me
match
text3But I want:
text1
prepend_me
match
text2
match
text3How do I get this?
2 Answers
Just count how often it got already matched and prefix it only on the first match:
perl -lpe 'print "prepend_me" if /^match$/ && ++$count == 1' text.txt 7 You could also do it with sed:
sed '0,/match/ s/\(match\)/prepend_me\n\1/' text.txt0,/match/is used to edit the text from the beginning (0) up to the first match ofmatch(/match/).s/\(match\)/prepend_me\n\1/capturesmatch(\(match\)) and replaces it with the desired text (prepend_me+ linebreak (\n) + captured match (\1)).