简体   繁体   中英

Perl search and replace: replacing end of line replaces beginning to line too

I have a file [data.txt] with the following data

a,b,c,d,e
e,f,g,h,i
j,k,l,m,n

I use the following perl command to replace the end of line with some text.

perl -pi -e 's/$/ X/g' data.txt

However, my file reflects the following (it replace the start of line too)

a,b,c,d,e X
 Xe,f,g,h,i X
 Xj,k,l,m,n X

This is unexpected, can anyone point out if I am missing anything obvious?

Cheers Saurabh

You could also rewrite it to:

perl -i -ple '$_ .= " X"' data.txt

which is easier to read in this case. I think. The -l option removes \\n from each line first and then adds it after (right before it -p rints) so you basically dont have to think about \\n .

When /m isn't used, $ is equivalent to (?=\\n\\z)|\\z .

As you can see, it can match at two different locations. For example, in the following, it can match at position 9 ( (?=\\n\\z) ) and at position 10 ( \\z ).

01234567890   <- positions
a,b,c,d,e␊

Solution: Remove the /g to only match the first of the two.

perl -pe's/$/ X/'

Solution: Remove the line feeds and match at the end of the string.

perl -ple's/\z/ X/'    # «$» would work as well as «\z», but I like to say what I mean.

Solution: Remove the line feeds and just use concatenation.

perl -ple'$_.=" X"'

Here is one way:

perl -pi -e 's/(.+)$/$1X/' data.txt

EDIT: Removed g as suggested. Also, with g removed, the solution can be simplified to

perl -pi -e 's/$/X/' data.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM