# Find and replace using parts of the found string in the replace string

Let `foo` be any string. I have to search a file for all occurrences of

``````   \LeftLabel{foo}
``````

and replace each occurrence with

``````   \LeftLabel{\textsf{foo}}
``````

but only if foo does not start with a `\$` character. How?

Let's consider this test file:

``````\$ cat file
\LeftLabel{foo}
\LeftLabel{\$foo}
LeftLabel{foo}
``````

Now, let's make the substitution:

``````\$ sed -E 's|\\LeftLabel\{([^\$}][^}]*)\}|\\LeftLabel{\\textsf{\1}}|g' file
\LeftLabel{\textsf{foo}}
\LeftLabel{\$foo}
LeftLabel{foo}
``````

### How it works

The substitute command in `sed` looks like `s|old|new|g` where `old` is a regular expression, `new` is what to substitute in its place and the final `g` tells sed to replace all such occurrences on a line, not just the first.

In our command, the `old` part looks like:

``````\\LeftLabel\{([^\$}][^}]*)\}
``````

This matches `\LeftLabel{` followed by any character other than `\$` or `}`, that is `[^\$}]`, followed by any number of any characters not `}`, that is `[^}]*`, followed by a `}`. Notice that some of those characters have to have a backslash in front of them so that sed treats them as normal characters, not regex-active characters. Notice also that the characters inside the curly braces are enclosed in parentheses. The parenthesis are regex-active characters which tell sed to save what's inside them as group 1. We can reference these characters as `\1` in the `new` part of the command.