Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

Comment on search and replace
Select or Download Code
Replies are listed 'Best First'.
Re: search and replace
by choroba (Canon) 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

    Cheers,

    JohnGG

      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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2015-09-04 02:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred temperature scale is:










    Results (128 votes), past polls