19

What does this command do?

grep "\bi\b" linux.txt

What is it searching for?

1
  • It may be obvious, but just in case it is not, here is a note on the (significant) difference between \<...\> and \b...\b: `You can get unexpected results if you assume the two patterns behave the same... see this link
    – Peter.O
    Commented Oct 16, 2011 at 18:23

3 Answers 3

23

\b in a regular expression means "word boundary".

With this grep command, you are searching for all words i in the file linux.txt. i can be at the beginning of a line or at the end, or between two space characters in a sentence.

3
  • can be in the begining or in the end?? isn't supposed to be only between spaces??
    – amyassin
    Commented Oct 16, 2011 at 19:43
  • 1
    I don't find more details about that. But trying by hand with a file containing the lines "i foo" and "bar i", the regexp provided to the grep command above is matching both of them.
    – uloBasEI
    Commented Oct 16, 2011 at 19:53
  • 1
    More precisely, not only space, but any non-word character. Just like the -w --word-regexp switch does: grep -w "i" linux.txt. For example a line like "<i>italic</i>" also matches.
    – manatwork
    Commented Oct 17, 2011 at 6:48
0

The \b (word boundary) anchor can be used in place of \< and \> to signify the beginning or end of a word.

If this is the content of a file:

Hi
this
is test file
to carry out few regular expressions

Then:

$ grep -e '\breg' file
to carry out few regular expressions
0

Note about \b , \<, \>:

When used inside quotes ("" or ''), \b and \<,\> work as word boundaries, as explained above.
When quotes are not used, \\b has to be used instead of \b.

Examples:
grep i works but does not find whole words only
grep \bi\b does not work
grep \\bi\\b works
grep "\bi\b" works and it is the same as grep "\<i\>"

1
  • Welcome to the site. If your post is meant to improve an existing answer rather than suggesting a different kind of solution, please don't post it as a new answer. Rather, place a comment below the answer you want to improve, or submit an edit suggestion that would incorporate your improvements to that answer.
    – AdminBee
    Commented Jan 3, 2022 at 13:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .