Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want grep all lines containing words that start with "H" and end with "d". How would i do that? I found that grep ^H will give me the H for everyline.

share|improve this question

migrated from Nov 4 '11 at 11:14

This question came from our site for professional and enthusiast programmers.

You want to learn regular expressions. – new123456 Nov 4 '11 at 11:19
It depends on how you define a word boundry, of course. – phogg Nov 4 '11 at 13:16

I would try: /^H.*d$/. The ^ is the starts with and $ end with. The .* matches anything.

share|improve this answer
sweet thanks man! I had to take off the "/" but that worked thanks again – aaron aaron Nov 3 '11 at 22:38

How do you define "words"?

If they're delimited by spaces:

grep '\<H[^ ]*d\>' ...

should do it. \< and \> match the beginning and end of a word, respectively. [^ ]* matches a sequence of zero or more non-space characters.

More, generally, if your grep supports it (GNU grep does):

grep '\<H[^[:space:]*d\>

finds words delimited by "space" characters: tab, newline, vertical tab, form feed, carriage return, and space.

I'm assuming that "lines containing word" means that you want "foo H123d bar" to match. If each line contains an entire word, replace \< by ^ and \> by $.

EDIT: This might not be 100% correct. \< and \> define a "word" as a non-empty sequence of letters, digits, and underscores. Define exactly what you mean by "word", and I'll try to refine my answer. In "*H*d*" is H*d a "word"?

share|improve this answer

You must log in to answer this question.