I have a string from a latex file that I would like to work on:

\title{This is the title}

I would like to save "This is the title" in a variable, but cannot manage to remove the substrings with the curly brackets, despite my attempts of escaping these.

title=`grep -F "\title" file.tex`

Neither of these work, and putting the curly brackets in single or double quotation mark doesn't either.

  • 2
    What operating system are you using? Do you have GNU grep? – terdon Apr 6 at 10:24

Assuming that $title is the string \title{This is the title}:


The { in the first parameter substitution does not need to be escaped (escaping it won't make it not work though), but the } in the second needs escaping. In the first one, you additionally need * to match the \title bit in the string, alternatively use ${title#\\title{} to delete the explicit string \title{.

You seem to get the % and # mixed up in your code, and you forgot the * in the substitution that removes the prefix string.

Assuming no title string spans more than a single line, you may get all those strings out of a document with

sed -n 's/.*\\title{\([^}]*\)}.*/\1/p' file

This matches (the first) \title{SOMETHING} on each line, and replaces the whole line with the SOMETHING substring. All other data is discarded.

| improve this answer | |

If you're using bash, you can use its regex facilities instead:

title='\title{This is the title}'
[[ $title =~ \{(.*)\} ]] && title=${BASH_REMATCH[1]}
echo "title=$title"

title=This is the title

That's, assuming you really need to do this in bash. If that stuff comes from a file, you better use tools better suited to extract and parse data from files, like grep, awk, perl, or tex itself.

| improve this answer | |

I wouldn't try to do this in the shell. Just parse the output of grep before saving in a variable:

title=$(grep -F '\title' file.tex | sed s'/.*{\(.*\)}/\1/')


title=$(grep -F '\title' file.tex | awk -F'[{}]' '{print $2}')

Or, if you have GNU grep, or any other implementation that supports -o and -P, you can do:

title=$(grep -oP '\\title\{\K[^}]+' file.tex)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.