You can just use something like:
sed 's/foo/barfoo/g' baz
( g at the end means global, each occurrence on each line, not just the first).
For an arbitrary (not fixed) pattern, such as foo[0-9] , you can use capture groups as follows:
pax$ echo 'xyz fooA abc xyz foo5 abc xyz fooB abc' | sed 's/\(foo[0-9]\)/bar\1/g' xyz fooA abc xyz barfoo5 abc xyz fooB abc
The brackets capture the actual text that matches the pattern, and \1 uses it as a wildcard.
You can use arbitrarily complex patterns with this, including matching only complete words. For example, only a template change if it is immediately surrounded by a word boundary:
pax$ echo 'xyz fooA abc xyz foo5 abc foo77 qqq xfoo4 zzz xyz fooB abc' | sed 's/\(\bfoo[0-9]\b\)/bar\1/g' xyz fooA abc xyz barfoo5 abc foo77 qqq xfoo4 zzz xyz fooB abc
In terms of how capture groups work, you can use parentheses to store text that matches the pattern for later use in replacement. Captured identifiers are based on characters ( reading from left to right, so regex (I left the escape characters \ and added it a bit for clarity):
( ( \S* ) ( \S* ) ) ^ ^ ^ ^ ^ ^ | | | | | | | +--2--+ +--3--+ | +---------1---------+
when applied to Pax Diablo text, you get three groups:
\1 = Pax Diablo \2 = Pax \3 = Diablo
as below:
pax$ echo 'Pax Diablo' | sed 's/\(\(\S*\) \(\S*\)\)/[\1] [\2] [\3]/' [Pax Diablo] [Pax] [Diablo]
paxdiablo
source share