Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have been researching this a lot, but I am still not clear on it. What does word boundary mean? What does it do?

So, for example, could someone explain this command to me please?

egrep '\b[A-Z]+\b' filename.sh
share|improve this question
1  
A "word boundary" is whatever the tool used defines as such... some consider nospace/space or space/nospace a word boundary, others consider a "word" as composed of [azA-Z0-9_]. Check the manual for egrep(1), perhaps the doumentation for the regular expressions in use. –  vonbrand Apr 7 '13 at 1:10

1 Answer 1

As described here, for example, it matches between words:

There are three different positions that qualify as word boundaries:

  1. Before the first character in the string, if the first character is a word character.
  2. After the last character in the string, if the last character is a word character.
  3. Between two characters in the string, where one is a word character and the other is not a word character.

Here are examples of each of those cases:

  1. For the string foobar, the first case matches

     foobar
    ^-----here
    
  2. For the string foobar, the second case matches

    foobar
          ^--here
    
  3. For the string foo bar, the third case will match

    foo bar
       ^--here, because space is not a word character
    

What qualifies as a word character depends on the specific regular expression implementation. In all cases however, letters ([a-z] and [A-Z]), numbers ([0-9]) and - are considered word characters.


So, the example regex you posted (\b[A-Z]+\b) means find the longest string that is between two word boundaries and that consists of upper case letters only. It might be easier to explain by example:

echo "FOOBAR" | egrep '\b[A-Z]+\b'   # Works
echo "FOO BAR" | egrep '\b[A-Z]+\b'  # Works
echo "aFOOBARb" | egrep '\b[A-Z]+\b' # Does not work, we want capitals only
echo "12345" | egrep '\b[A-Za]+\b'   # Does not work, no letters
echo "1FOOBAR2" | egrep '\b[A-Z]+\b' # Does not work, 1 and 2 are word chars
echo "-FOOBAR-" | egrep '\b[A-Z]+\b' # Does not work, - is a word char
echo "#FOOBAR$" | egrep '\b[A-Z]+\b' # Works, # and $ are not word chars
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.