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

Hi monks, Is there a way search and replace a list of elements with another in a file using perl.

Replies are listed 'Best First'.
Re: Search and replace
by mirod (Canon) on Mar 26, 2009 at 08:16 UTC

    more seriously, we need a bit more information in order to help you: what are "elements"? Are you talking about replacing tag names in some marked-up text (HTML, XML...) or just plain strings?

    For plain strings a variation of perl -i.bak -p -e's/foo/bar/g' my_file would work.

    For tagged text, use of an XML/HTML parser is usually advised. An example would be perl -MXML::Twig -e'XML::Twig->parse( twig_handlers => { foo => sub { $_->set_tag( "bar") }, $ARGV[0])->print' my_file.xml > new_file.xml (also works with HTML).

    Both examples use unix quotes, I guess you need to swap ' and " in windows.

    And of course the real thing would probably not be a one-liner, start with use strict; use warnings;, set up a hash initial_element => replacement... try it, and if you hit a problem, show us your code, the initial data, the output and the expected output and we will be able to help.

Re: Search and replace
by irah (Pilgrim) on Mar 26, 2009 at 08:09 UTC
    perl -pi -e 's/searchterm/replaceterm/' *.c perl -pi -i.bak -e 's/searchterm/replaceterm/' *.c
Re: Search and replace
by mirod (Canon) on Mar 26, 2009 at 08:08 UTC

    yes