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.
perl -pe 'print "*inserted text*\n" if /\[option]/'
orperl -pE 'say "*inserted text*" if /\[option]/'
– Sundeep Nov 17 '20 at 14:08perl -lpe 'print "Hello World" if /^\[option\]$/' input
– Mario Palumbo Nov 18 '20 at 08:44