2

I am trying to search for some strings in a file and replace them using perl:

perl -pe "s/filename/$FNAME/" Header.xml > $HDIR/$FNAME.xml

How can I search and replace multiple string, since adding another commands just overwrites the output file:

perl -pe "s/RBRef/$REF/" HeaderRBRS.xml > $HDIR/$FNAME.xml
perl -pe "s/MessageIdentifier/$MessageIdentifier/" HeaderRBRS.xml > $HDIR/$FNAME.xml
perl -pe "s/FileDigestValue/$digestNr/" HeaderRBRS.xml > $HDIR/$FNAME.xml
perl -pe "s/filename/$FNAME/" HeaderRBRS.xml > $HDIR/$FNAME.xml

In the last case only perl -pe "s/filename/$FNAME/" HeaderRBRS.xml > $HDIR/$FNAME.xml will be executed every time.

Thanks in advance.

Myh
  • 95
  • 1
  • 9
  • 1
    you should write a perl script and pass in an array of strings to search and replace. – Mike Tung Dec 04 '18 at 13:01
  • 1
    You should use a proper library to handle XML files. – choroba Dec 04 '18 at 13:02
  • 1
    Also, by using double quotes, you're building the Perl code from the shell variable. If the variable contains a slash, the code will break. Using Perl variables would work better, as they're real variables, not just expanding macros. – choroba Dec 04 '18 at 13:04
  • What library? @choroba – Myh Dec 04 '18 at 15:02
  • I'm a fan of [XML::LibXML](http://p3rl.org/XML::LibXML), but [XML::Twig](http://p3rl.org/XML::Twig) isn't bad either. – choroba Dec 04 '18 at 23:04

1 Answers1

1

Pass all substitutions as one argument after -e. Delimit them by a semicolon ;.

perl -pe "s/filename/$FNAME/;s/RBRef/$REF/;..." infile > outfile
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • Thank you, it is working. Do you know how to escape $ sign if the variable $FNAME contains this character in it? – Myh Dec 04 '18 at 13:27
  • @MihaiDumitru Yes, in `bash` write `${FNAME//$/\\$}` instead of `$FNAME`. Also see https://stackoverflow.com/a/16951928/6770384 for a more general quoting mechanism. – Socowi Dec 04 '18 at 13:30
  • Thank you, you are a life saver! – Myh Dec 04 '18 at 13:40