UFC Insider
UFC Insider

Reputation: 838

What's wrong with my usage of grep?

I'm executing the following command:

echo "ze2s hihi" | tr ' ' '\n' | grep 'h*'

but instead of getting hihi in the output I'm getting this:

ze2s
hihi

What's wrong?

Upvotes: 0

Views: 64

Answers (4)

Ed Morton
Ed Morton

Reputation: 204124

You got the answer to your question but FYI you don't need multiple commands and pipes to do what you want:

$ echo "ze2s hihi" | awk -v RS='\\s+' '/h/'
hihi

The above uses GNU awk for multi-char RS and \s for space chars.

Upvotes: 1

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21502

The asterisk matches the preceding item zero or more times. Thus h* matches h zero or more times, i.e. anything.

If you want to match h and any characters after it, use h.* expression, where the period matches any single character.

Upvotes: 2

CDe
CDe

Reputation: 181

Consider using egrep or grep -E if you only want to have the lines with h* at the beginning:

echo "ze2s hihi" | tr ' ' '\n' | egrep '^h'

Upvotes: 2

Jeremy Gurr
Jeremy Gurr

Reputation: 1623

What you want is:

echo "ze2s hihi" | tr ' ' '\n' | grep 'h.*'

With "h*" you are asking to match any number of h's in a sequence, including 0 h's, which ze2s matches.

Or maybe you just want to match anything which contains an h:

echo "ze2s hihi" | tr ' ' '\n' | grep 'h'

Upvotes: 2

Related Questions