# extracting strings from LaTeX files

I am searching for the whole evening, but couldn't find a solution. (I also read Remove a specific latex command from the text AND closing bracket behind it)

I have a lot of LaTeX files from which I would love to extract the argument of a special command into second file.

Please imagine, a LaTeX file with lots of "short" lines, i.e. a line break all 80 chars. Thus it is more than likely, that the argument of the command in question, spans more than one line in the source file. Furthermore, there might be some extra LaTeX commands with additional curly braces, which should be extracted as well.

Lorem ipsum dolor sit amet, \ltxcmd{consetetur sadipscing} elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
erat, sed diam voluptua. At vero eos et accusam et justo \ltxcmd{duo
dolores \emph{et ea rebum}}. Stet clita kasd gubergren, \ltxcmd{sea takimata
\textbf{sanctus} \emph{est} Lorem} ipsum dolor sit amet. Lorem ipsum dolor sit
amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea
rebum.

This should return the three arguments as follows:

{duo dolores \emph{et ea rebum}}
{sea takimata \textbf{sanctus} \emph{est} Lorem}

I tried first

cat file1.tex | sed -n 's/.*\\ltxcmd$${[[:alnum:] ]*}$$.*/\1/p'

but this ended searching at the line end, therefore I tried

tr \n ' ' < file1.tex | sed -n 's/.*\\ltxcmd$${[[:alnum:] ]*}$$.*/\1/p'

which returned the first occurance, but leaves the rest untouched.

Next try was to a gat the end of the sed expression, in order to start the search anew -- not helpful.

Any hints? bash and sed would be welcome.

• Bash isn’t much of a text editor – Jeff Schaller Apr 4 '18 at 21:36
• Jeff, I know, but they are both programmable. I have to work on >50 files on this project, any automatic help would be appreciated. I wasn't even able, to get sed to search beyond the line break. When I used tr to remove the line end, I ended up with only the first result, skipping the remaining targets in that file. :-( – Jan Apr 4 '18 at 21:43
• You need a recursive decent parser here, you can write it with or without a regex. Either way, wouldn't want to do this in bash. – Evan Carroll Apr 4 '18 at 22:45
• Think this probably more belongs on TeX - LaTeX – Evan Carroll Apr 4 '18 at 22:53
• @EvanCarroll this could be any kind of programming language, it just happens in my case to be LaTeX. I tried something like tr "\n" " " < infile | sed -n 's/.*\\ltxcmd$${[[:alnum:] ]*}$$.*/\1/p', in my bash, but this prints only the first occurance and misses every other occurance. Of course, this was just a POC. If if succeeded, I would have added find . -name *.tex - exec ... {};` also ... – Jan Apr 5 '18 at 4:53