3

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?

0
6

The command line option -p means that the file is processed line by line, i.e. what you do is basically:

while (<>) {
     s/text2\n\z/text3/s;
     print $_
}

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:

perl -e 'local $/; (my $x = <>) =~s{text2$}{text3}; print $x' text.txt
4
  • You can explain this syntax please? – Mario Palumbo Dec 21 '20 at 9:52
  • @MarioPalumbo: can you please describe what exactly you don't understand on this syntax? – Steffen Ullrich Dec 21 '20 at 9:53
  • Sorry LOL, I not have understand the meaning of assignment var = "<>" and the meaning of "$/" – Mario Palumbo Dec 21 '20 at 9:55
  • 2
    @MarioPalumbo: local $/ sets $/ implicitly to undef . $/ is the INPUT_RECORD_SEPARATOR which by default is newline but is now changed to undef - which means that <> slurps in the whole file. See perldoc perlvar for details, which also includes examples with similar code as I've used. – Steffen Ullrich Dec 21 '20 at 9:58
4

There is no need to slurp in the entire file. Use this Perl one-liner:

perl -lpe 's{text2}{text3} if eof ' in_file

Prints:

text1
text2
text1
text2
text1
text3
0

The solution that I have adopted is:

perl -0pe 's/text2\s*$/text3\n/' text.txt
6
  • Please don't add "thank you" as an answer. Instead, accept the answer that you found most helpful. - From Review – Pilot6 Dec 21 '20 at 21:08
  • I have already accepted the answer – Mario Palumbo Dec 22 '20 at 8:52
  • But you posted this as another answer. This looks like a comment to the accepted answer. – Pilot6 Dec 22 '20 at 9:13
  • No, this is the solution that i have adopted. – Mario Palumbo Dec 22 '20 at 11:25
  • please note that the code of my answer is different. – Mario Palumbo Dec 22 '20 at 11:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.