I have a file, file1.tex, containing TeX commands, like \em and \par. All of the commands are in the format \ + some string of uppercase and lowercase letters from A-Z and are all followed by a space.
I need to use a command like this, which replaces all spaces with \, a slash and a space.
sed -i "s/\ /\\\\\ /g" ./file1.tex
I do not want these to replace the empty spaces which appear immediately after TeX commands though. For example, I want this:
\noindent This is a sentence {\em which has some words}.
This is another \hfill sentence \ldots with some more words.
To become:
\noindent This\ is\ a\ sentence\ {\em which\ has\ some\ words}.
This\ is\ another\ \hfill sentence\ \ldots with\ some\ more\ words.
How can I replace all spaces, except those appearing after any command taking the form of \sometext?
Since
seddoesn’t support look-behind, I think this will be a lot easier using Perl.To make the changes permanent to the file in-place:
Explanation:
The regex matches a word which does not start with a backslash which is followed by a space.
\b– word boundary(?<!– begin a non-capturing negative look-behind (don’t match)\\– escaped backslash)– close the look-behind(– begin a capture group\w+– match one or more word characters (alphanumeric plus underscore))– close the capture group$1– copy the capture group into the replacement\\– add a backslashg– do the substitution globallyI left a couple things out of the list which should be self-evident.