Search code examples
xmlxpathxmlstarlet

How to print newline inside concat of xmlstarlet


I want to separate my output with a newline, so I tried:

xmlstarlet sel -t -m "//node01" -v 'concat(@title,"\n",script/code)' -n input.xml

However, what is printed is the "\n" literal value and the output is on same line. How do I force a newline within the concat() function?

A sample input.xml is:

<test>
<aaa>This is a test</aaa>
<node01 title="howdy">
    <script>
        <code>function idoit() {
                console.log("hello world");
            }
        </code>
    </script>
</node01>
</test>

And when I run, the output is:

howdy\nfunction idoit() {
                console.log("hello world");
            }

Solution

  • You can give a literal newline in the argument, the syntax for this is shell-specific.

    • This should work in any POSIX sh:

      xmlstarlet sel -t -m "//node01" -v 'concat(@title,"
      ",script/code)' -n input.xml
      
    • In bash, you can use $'ANSI C Quoting':

      xmlstarlet sel -t -m "//node01" -v $'concat(@title,"\n",script/code)' -n input.xml
      

    Another trick which is not shell-specific is to set an XPATH variable with newline as the value:

    xmlstarlet sel -t --var nl -n -b -m "//node01" -v 'concat(@title,$nl,script/code)' -n input.xml