4

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

2 Answers 2

7

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

2
  • Thanx, it works very nice. It's the first time I meet xmlstartlet...
    – user41063
    Feb 25, 2018 at 18:29
  • @user41063, you're welcome Feb 25, 2018 at 18:57
2

You can overcome the issues of / in the pattern text by using a different delimiter such as # e.g.

sed '\#^</fontconfig>#i\
  <dir>/usr/local/texlive/texmf-local</dir>\
  <dir>/usr/local/share/fonts</dir>
' 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>
  <dir>/usr/local/texlive/texmf-local</dir>
  <dir>/usr/local/share/fonts</dir>
</fontconfig>

You must log in to answer this question.

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