1

Referring to the link: How to insert text after a certain string in a file? I have this input file:

Some text
Random
[option]
Some stuff

I want a line of text before "[option]":

Some text
Random
Hello World
[option]
Some stuff

This command:

sed  '/\[option\]/i Hello World' input

Works,
but this command:

perl -pe '/\[option\]/i Hello World' input

does not work.
What is the equivalent perl command?

Update:

I have found this partial solution thanks to @terdon and @Sundeep:

perl -lpe 'print "Hello World" if /^\[option\]$/' input

But I want to insert the text string only the first time it encounters "[option]", not always.
For example:

Some text
Random
[option]
Some stuff
test1
[option]
test2

Become:

Some text
Random
Hello World
[option]
Some stuff
test1
Hello World
[option]
test2

And not:

Some text
Random
Hello World
[option]
Some stuff
test1
[option]
test2

as I want.

Mario Palumbo
  • 233
  • 1
  • 14

2 Answers2

3

Here's one perl approach:

$ perl -ne 'if(/\[option\]/){print "*inserted text*\n"}; print' input
Some text
Random
*inserted text*
[option]
Some stuff

And here's another, more concise one:

 $ perl -ne '/\[option\]/?print "*inserted text*\n$_":print' input
Some text
Random
*inserted text*
[option]
Some stuff

This one requires you to read the whole file into memory:

$ perl -0777 -pe 's/\[option\]/*inserted text*\n$&/' input 
Some text
Random
*inserted text*
[option]
Some stuff
terdon
  • 242,166
1

Thank you @terdon and @Sundeep! This is the form I was looking for:

perl -lpe 'print "Hello World" if /^\[option\]$/' input

Update:

I want to insert the text string only the first time it encounters "[option]", not always.
I have found the solution:

perl -lpe 'print "Hello World" if /^\[option\]$/ && ++$i == 1' input

For append a text instead I can use the command:

perl -lpe '$_ .= "\nHello World" if /^\[option\]$/ && ++$i == 1' input

&& is the and of the if, while "++" or "--" means increment or decrement of 1. Since the variable i (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. "&&" has higher precedence than "and". The second condition is evaluated only if the first is satisfied. So in this case the value of the variable is incremented and compared only if a match occurs.

Mario Palumbo
  • 233
  • 1
  • 14