Yes.
$ sed 's/\<Hit\>/OK/g' file
asdasdasdHit Hitasdasd OK OK
Hitasda OK OK asdaHit OK OK
OK Hitasda OK
...
...
The \<
will match a zero-length word boundary at the beginning of a word, and \>
will do the same at the end of a word.
The zero-length-ness of \<
and \>
means that they won't match any character in and of themselves, but forces the adjoining pattern to match on a word boundary.
A word boundary is a point in a string where an alphanumeric character is adjacent to a non-alphanumeric character, such as the point between ␣
(a space) and H
and the point between t
and ␣
(another space) in the string ␣Hit␣
, or the point between the t
and the immediately following newline on all three
lines in the example data.
With GNU sed
you may use \b
in place of \<
and \>
(though it also understands \<
and \>
):
$ sed 's/\bHit\b/OK/g' file
... but BSD sed
doesn't understand \b
.
\b
, just change sed withperl -pe
keeping all the rest command as it is and will work everywhere.... – George Vasiliou Apr 05 '17 at 20:16\<
and\>
and it will work insed
on both Linux and BSD... Perl is a bit heavier to start and run. – Kusalananda Nov 28 '19 at 10:48\<
and\>
. E.g.,echo "foobar" | sed "s/\<foobar\>/bazqux/g"
yieldsfoobar
. – weberc2 Apr 16 '21 at 13:27\<
and\>
with the nativesed
on OpenBSD. It seems to fail on macOS, so I'm assuming you're on macOS or FreeBSD, right? – Kusalananda Apr 16 '21 at 14:39