bash

How to break a xml line into several lines using bash script?


I'm a beginner in bash script and cannot solve the following problem: I have a file where each line is a xml file. I would like to divide each line into several lines.

For instance, I would like to put the following line:

<LumiBlockCollection><Run>201556</Run><LBRange Start="1020" End="1030"/></LumiBlockCollection>

into the format:

<LumiBlockCollection>
<Run>201556</Run>
<LBRange Start="1020" End="1030"/>
</LumiBlockCollection>

Does anyone know how to solve this problem?


Solution

  • In general, for a robust solution that works with varying input data, you should use an XML parser for this task:


    A solution based on xmllint - xmllint is a standard utility on macOS and some Linux distros (e.g., Fedora):

      echo '<LumiBlockCollection><Run>201556</Run><LBRange Start="1020" End="1030"/></LumiBlockCollection>' \
        | XMLLINT_INDENT= xmllint --format - | tail -n +2
    

    If your Linux distro does not come with xmllint, chances are that it can be installed with your platform's package manager; e.g., on Debian-based distros such as Ubuntu: sudo apt-get install libxml2-utils


    Another solution, based on third-party utility xmlstarlet:

    echo '<LumiBlockCollection><Run>201556</Run><LBRange Start="1020" End="1030"/></LumiBlockCollection>' \
      | xmlstarlet fo --omit-decl --noindent
    

    Obtaining xmlstarlet: