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.
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
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,
--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
$ 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.
-o option to
grep will make it only return the matched string, not the whole line.
$ grep -o '\<b[[:lower:]]*ch[[:lower:]]*' file
^s.*ch will match any line that starts with
s and contains
ch anywhere else on the same line.