M HYPE SPLASH
// news

perl command: Prepend a line of text only at the first occurrence

By Emma Valentine

I have this input file:

text1
match
text2
match
text3

And I have this command:

perl -lpe 'print "prepend_me" if /^match$/' text.txt

And its output is:

text1
prepend_me
match
text2
prepend_me
match
text3

But I want:

text1
prepend_me
match
text2
match
text3

How 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.txt
  • 0,/match/ is used to edit the text from the beginning (0) up to the first match of match (/match/).

  • s/\(match\)/prepend_me\n\1/ captures match (\(match\)) and replaces it with the desired text (prepend_me + linebreak (\n) + captured match (\1)).

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy