0

How to insert a newline character after each occurrence of a specific XML tag in a file?

My file has multiple tags </Data> and I want to insert a NewLine character after each </Data> tag

I've been trying various combinations with sed but it never inserts the newline character :(

The latest was sed '/<\/Data\>/ a \n'

Thanks!

5 Answers 5

1
sed 's:</Data>:&\
:g'

Or when calling sed from bash or other shell that supports $'\<char>' to expand an escape sequence:

sed 's:</Data>:&\'$'\n'':g'

Or with GNU sed:

sed 's:</Data>:&\n:g'

e.g.:

$ printf 'foo</Data>bar</Data>etc\n'
foo</Data>bar</Data>etc
$
$ printf 'foo</Data>bar</Data>etc\n' | sed 's:</Data>:&\n:g'
foo</Data>
bar</Data>
etc
0
0

This might not be the most elegant but it works:

sed 's/\(<\/Data>\)/\1\n/ig'
0

sed '/<\/Data>/ a \\n' will insert the newline, however, if the string exists more than once in a line (typical xml may be one long line) it simply appends a newline after it instead of after every occurrence.

If you really want a newline after every occurrence, sed 's/\(<\/Data>\)/\1\n/g' should do the trick.

0

Instead of just formatting the Data tag, you can format the whole XML file with newlines after each XML nodes. This is the proper solution.

Using is not elegant and not universal nor a proper solution.

Think of a CDATA section from within your XML with:

<![CDATA[foobar</Data>qux]]>

Instead, using an XML parser like xmlstarlet:

xmlstarlet format -R file.xml

Example:

cat file.xml
<foo>
<a>jkj</a><data>fghj</data><x>w</x>
</foo>

$ xmlstarlet fo -R file
<?xml version="1.0"?>
<foo>
  <a>jkj</a>
  <data>fghj</data>
  <x>w</x>
</foo>
0

Tried in python

cat inputfile

san</Data>abhi</Data>san

Python

#!/usr/bin/python
g="</Data>"
import re
k=open('k.txt','r')
for i in k:
    m="{0}".format(g+"\n")
    q=re.sub(g,"{0}",i).format(m)
    print q

output

san</Data>
abhi</Data>
san

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .