0

I need to find the word beach, how would I specify that it starts with b and contains ch? I have tried using grep '^s.*ch' but that prints out lines that contain it and I just want the word.

2 Answers 2

1

The problem you have is that .* matches any sequence of characters (maybe omitting newline) including spaces.

So you want to change this to something which matches just characters which make up a word. How exactly you do this depends on which implementation of regular expressions you are using, and if you want to consider characters from different alphabets. One reasonably portable way is to use [[:alpha:]]*

The syntax to match at the start of a word also depends on the implementation. For grep you can use \<.

To just get the word there are two options to grep that can help, -o and --color. The former just outputs what is matched and the latter puts out the entire line with the match highlighted.

So you probably want

grep -o '\<b[[:alpha:]]*ch' filename
1
  • Well explained, your added info was especially useful.
    – C. Medina
    Feb 12, 2017 at 20:45
1
$ grep -o '\<b[a-z]*ch[a-z]*' file

This will fetch all words that starts with b and contains ch. The two [a-z]* will match any number of lowercase letters. The \< will ensure that the b is the first letter in the word.

The -o option to grep will make it only return the matched string, not the whole line.

Alternative:

$ grep -o '\<b[[:lower:]]*ch[[:lower:]]*' file

Your pattern, ^s.*ch will match any line that starts with s and contains ch anywhere else on the same line.

1
  • Very helpful. Completely answered my question!
    – C. Medina
    Feb 12, 2017 at 20:39

You must log in to answer this question.

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