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.

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
| improve this answer | |
  • Well explained, your added info was especially useful. – C. Medina Feb 12 '17 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.

| improve this answer | |
  • Very helpful. Completely answered my question! – C. Medina Feb 12 '17 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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