[Tex/LaTex] Most useful sed one-liners for TeX users

editors

The title of the question says it all. What is your favorite sed one-liner when it comes to editing TeX files. I have seen at least one sed goodfella on this forum who is writing a book about a sed in TeX. Maybe he could volunteer some of his tricks?

I promise mine are coming soon (I love using sed for editing!).

Best Answer

I mostly use sed for searching & replacing within TeX files in whole directories. For example:

find "." -name "*.tex" | xargs sed -i -e "s/\(\\usepackage\){times}/\1{mathptmx}/g"

This changes all occurrences of \usepackage{times} into \usepackage{mathptmx}, to enable Times font both for text and for math.

  • find searches all .tex files
  • the pipe symbol | allows using the output of one command as input of another
  • xargs takes the list of file names, returned by find, and makes them into one line
  • sed applies the desired change for each file contained in that line. I use options
    • -i for in-place editing (you could specify a suffix for making backups)
    • -e for executing a script, here s/.../.../.. for search & replace
  • sed understands regular expression syntax, here I additionally used backslashes \ for quoting some characters with a special meaning for the shell, such as parentheses and the backslash itself
  • The backslash \ at the end of the first line is for breaking the line, for better displaying here. You don't need it if you type all into one command line.

For such frequently used command lines I usually create a shell function or a shell script, so I don't have to type much and just call my function/script with a regular expression as argument.

Related Question