Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

How to modify words in a line using perl oneliner

by Anonymous Monk
on Sep 30, 2009 at 10:16 UTC ( #798278=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I would like to modify the word "first" into "last" in the second line of file one.txt could you kindly help.

Input File(one.txt)
#verify_custom fleet part=first base=first after base

I tried the following perl one liner, but it did not help. perl -ni.bak -e 'print s/first/last/' one.txt
Expected Output: #verify_custom fleet part=last base=last after base
Thanks a lot.

Replies are listed 'Best First'.
Re: How to modify words in a line using perl oneliner
by ccn (Vicar) on Sep 30, 2009 at 10:20 UTC
    perl -i.bak -pe 's/first/last/g' one.txt

    To make your code work you need to change the order of operators and add 'g' modifier to the regexp

    perl -ni.bak -e 's/first/last/g; print' one.txt

      Maybe also add in boundaries, just in case? Firstly, blast, etc...

      perl -ni.bak -e 's/\bfirst\b/last/g; print' one.txt
      Just a something something...
      ...or even, assuming ...second line... to be a specific requirement (c/w a statement of the loaction of the string to be changed):
      perl -ni.bak -e 's/first/last/g if $. == 2; print' one.txt
      A user level that continues to overstate my experience :-))
Re: How to modify words in a line using perl oneliner
by vitoco (Friar) on Sep 30, 2009 at 14:21 UTC

    What you are printing is the number of substitutions on each line, ie. "1" when "first" is found, and undef (nothing) when not. A value of "2" would be returned for line 2 if "g" modifier were used.

    Prefer -p option instead of -n for this kind of one-liners. In this case, the output should be:

    perl -pi.bak -e 's/first/last/' one.txt #verify_custom fleet part=last base=first after base

    realizing that "g" modifier is missing if both "first" words must be changed at the same time.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://798278]
Approved by herveus
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2020-07-10 09:17 GMT
Find Nodes?
    Voting Booth?

    No recent polls found