1

Looking at text below, how do I go about replacing multiple lines of text?

<Model500>
ABC
BCD 
CDE
</Model500>
<Model500>
123
234
345
</Model500>

The output could be like below

<Model500>
AAA
BBB 
CCC
</Model500>
<Model500>
111
333
555
</Model500>

I would like to accomplish this with sed but any command line utility that works with Bash will work. Should I be using a loop to accomplish this?

  • 1
    bash has a lot of features, but it's not a text editor – Jeff Schaller Sep 13 '16 at 20:44
  • 2
    what's the rule? – Ipor Sircer Sep 13 '16 at 20:46
  • Well I do understand that the bash is not supposed to be used for extensive text editing, but I thought one can use 'sed' for that purpose? – keyboard_solo Sep 13 '16 at 20:48
  • 1
    I got confused when you said "any bash method" -- bash != sed – Jeff Schaller Sep 13 '16 at 20:53
  • 1
    Are the replacements based on rules, or is the end result not related to the initial values? – Jesusaur Sep 13 '16 at 21:07
9

Use a proper tool, in shell, is a good one :

xmlstarlet edit -L -u "//Model500[1]"  -v "AAA                                                                
BBB
CCC" file.xml

xmlstarlet edit -L -u "//Model500[2]" -v "111                                                               
333
555" file.xml


cat file.xml

The expression //Model500[2] is a Xpath expression

NOTE ¹

you need to enclose your xml with a tag like :

<root>
...
</root>

to be XML valid. I hope you cutted the XML file for the purpose of your question.

NOTE ²

You can also use , , etc... and a proper xml lib.

In :

#!/usr/bin/perl

use strict;
use warnings;

use XML::Simple;

my $xml_file = 'file.xml';

my $xml = XMLin(
    $xml_file,
    KeepRoot => 1,
    ForceArray => 1,
);

$xml->{root}->[0]->{Model500}->[0] = "AAA\nBBB\nCCC\n";
$xml->{root}->[0]->{Model500}->[1] = "111\n222\n333\n";

XMLout(
    $xml,
    KeepRoot => 1,
    NoAttr => 1,
    OutputFile => $xml_file,
);
  • Woah I have not heard of this tool but the format on this seems much more intuitive. Thanks. I will give this one a try. – keyboard_solo Sep 13 '16 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.