1

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 2

3

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
  • Can you explain this sintax, please? Nov 18, 2020 at 11:27
  • 1
    @MarioPalumbo: I have no idea what you don't understand on this syntax because it is basic Perl. Maybe you should learn Perl first? Nov 18, 2020 at 12:23
  • Thank you @Steffen. I am ashamed of my previous comment. && is the and of the if, while "++" or "--" means increment or decrement of 1. Since the variable count (it could be any other variable) starts from 0 by default and the increment is made in prefix notation, it means that the variable is first incremented and then the first comparison is made. This syntax makes the command very elastic and is more powerful than I thought. Nov 18, 2020 at 13:12
  • I have studied that "&&" has higher precedence than "and" and have also seen some practical examples. Thank you very much @Steffen Nov 18, 2020 at 13:54
  • 1
    @MarioPalumbo: fully correct. Nov 18, 2020 at 22:33
1

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
  • 1
    I already know sed syntax for this but I prefer perl for some reasons. Equally an upvote for you. Nov 18, 2020 at 23:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .