Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

How to modify words in a line using perl oneliner

by Anonymous Monk
on Sep 30, 2009 at 10:16 UTC ( [id://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 (Hermit) 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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-04-23 07:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found