Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

search and replace

by Peamasii (Sexton)
on Sep 28, 2012 at 07:49 UTC ( #996129=perlquestion: print w/replies, xml ) Need Help??
Peamasii has asked for the wisdom of the Perl Monks concerning the following question:

HI, I need to do a search and replace across many text files with a command like:
perl -i.bak -p -es/old/new/g *.sh
However the text I need to replace is:
mail xmlfeedback -s "feed invalid for agent 1027"
with this:
mail -s "feed invalid for agent 1027" xmlfeedback
where the agent # is different in every file. How can I write the regex to locate and switch the order of the words as required above? thanks in advance

Replies are listed 'Best First'.
Re: search and replace
by choroba (Chancellor) on Sep 28, 2012 at 08:06 UTC
    Just remove the "xmlfeedback" and add it to the end of the line if the line matches:
    perl -pe 's/xmlfeedback //,s/$/ xmlfeedback/ if /^mail xmlfeedback -s +"feed invalid for agent .*"/'
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: search and replace
by johngg (Abbot) on Sep 28, 2012 at 08:10 UTC

    Something like this perhaps.

    perl -pi.bak -e 's/^(mail)( xmlfeedback)(.*)/$1$3$2/' *.sh



      Thank you, this solution worked great! I didn't dive into the Regexp solutions because I suspected there was a simple way to switch those tokens around just like this solution does. I just couldn't find an example anywhere. Thanks again for everyone's help.
Re: search and replace
by Anonymous Monk on Sep 28, 2012 at 08:12 UTC

    Dude, perlrequick, Regexp::English, Regexp::Common, Iterator::Files, ARGV::readonly

    s{^\Qmail xmlfeedback -s \E(.*)$}{mail -s $1 xmlfeedback}sgx; s{^mail xmlfeedback -s ("feed invalid for agent \d+")\s*$}{mail -s $1 +xmlfeedback}sgx;

    use Regexp::English; my $re = Regexp::English -> start_of_line -> literal('mail xmlfeedback -s') -> remember -> literal('"feed invalid for agent ') -> multiple -> digit -> end -> literal('"') -> end -> zero_or_more -> whitespace_char -> end -> end_of_line; print $re; __END__ (?^:^mail\ xmlfeedback\ \-s(\"feed\ invalid\ for\ agent\ (?:\d+)\")(?: +\s*)$)
      use Regexp::English; my $re = Regexp::English -> start_of_line -> literal('mail xmlfeedback -s ') -> remember -> zero_or_more -> non_newline -> end -> end_of_line; print $re; __END__ (?^:^mail\ xmlfeedback\ \-s\ ((?:(?s)[^\n]*)$))

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://996129]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2017-04-30 07:34 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (534 votes). Check out past polls.