I have this text file or sdout:
text1
text2
text1
text2
text1
text2
I have this code:
perl -pe "s/text2\n\z/text3/s" text.txt #Note the modifier "/s"
I with \z expect him to understand that this is the last line before the eof and consequently I expect:
text1
text2
text1
text2
text1
text3
But instead it returns:
text1
text3text1
text3text1
text3 #without final newline
What am I doing wrong?
The command line option
-p
means that the file is processed line by line, i.e. what you do is basically:Therefore the
\z
does not match the end of all input data but the end of each line.What you likely need is not to use
-p
but instead read the full file and replace only the end. Note that the regex can be simplified by just using$
and/s
and\z
are not needed:There is no need to slurp in the entire file. Use this Perl one-liner:
Prints:
The solution that I have adopted is: