Insert some lines before a specific line with sed

sedxml

I've the following file

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/usr/local/texlive/2017/texmf-dist/fonts/opentype</dir>
  <dir>/usr/local/texlive/2017/texmf-dist/fonts/truetype</dir>
  <dir>/usr/local/texlive/2017/texmf-dist/fonts/type1</dir>
</fontconfig>

and I've to add the following lines:

  <dir>/usr/local/texlive/texmf-local</dir>
  <dir>/usr/local/share/fonts</dir>

before the closing tag /fontconfig>. I'm not sure that it's always on 7th line, so I must look for it as a string. I've some troubles in these strings with <> and / … How can I solve with sed? thanx

Best Answer

Don't use sed, awk and alike for parsing XML/HMTL data - it'll never come to robust and scalable result. Use a proper XML/HTML processors.
The right way with xmlstarlet tool:

xmlstarlet ed -s '//fontconfig' -t elem -n 'dir' -v '/usr/local/texlive/texmf-local' \
-s '//fontconfig' -t elem -n 'dir' -v '/usr/local/share/fonts' input.xml

The output:

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/usr/local/texlive/2017/texmf-dist/fonts/opentype</dir>
  <dir>/usr/local/texlive/2017/texmf-dist/fonts/truetype</dir>
  <dir>/usr/local/texlive/2017/texmf-dist/fonts/type1</dir>
  <dir>/usr/local/texlive/texmf-local</dir>
  <dir>/usr/local/share/fonts</dir>
</fontconfig>

To modify/edit the file in-place - add -L option: xmlstarlet ed -L ....


For more details type: xmlstarlet ed --help

Related Question