10

Lets say I try to replace in a like this

asdasdasdHit Hitasdasd Hit Hit
Hitasda Hit Hit asdaHit Hit Hit
Hit Hitasda Hit
...
...

Is there a way to get every "clean" Hit replaced with OK? I tried /g but then everything gets an OK With s/\ Hit\ /OK/g the Hit on the newline gets lost.

don_crissti
  • 82,805
JDizzle
  • 247

1 Answers1

18

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.

Kusalananda
  • 333,661
  • 3
    For your last comment about BSD sed that does not understand \b, just change sed with perl -pe keeping all the rest command as it is and will work everywhere.... – George Vasiliou Apr 05 '17 at 20:16
  • 1
    @GeorgeVasiliou Or keep using \< and \> and it will work in sed on both Linux and BSD... Perl is a bit heavier to start and run. – Kusalananda Nov 28 '19 at 10:48
  • @Kusalananda I don't think BSD said understands \< and \>. E.g., echo "foobar" | sed "s/\<foobar\>/bazqux/g" yields foobar. – weberc2 Apr 16 '21 at 13:27
  • @weberc2 What BSD system are you on? I'm able to use \< and \> with the native sed 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
  • @Kusalananda macOS. Womp womp. – weberc2 Apr 16 '21 at 16:18