Motorahead
Motorahead

Reputation: 75

Bash scripting. grep with wildcard not working

Within bash, I'm trying to search (grep) the output of a command (ntp), for a specific string. However, one of the columns in the output is constantly changing. So for that column it could be any character.

I'm probably not doing this correctly, but the * is not working like I hoped.

ntpq -p | grep "10 l * 64  377  0.000  0.000  0.001"

The asterisk is replacing a column that changes from - to 1-64, by the second.

any help would be much appreciated!

Upvotes: 1

Views: 4866

Answers (1)

jordanm
jordanm

Reputation: 34934

A * in regex is different from a * in shell globbing. The following is from the regex(7) manpage:

An atom followed by '*' matches a sequence of 0 or more matches of  the  atom.

This means that in your regex, you are saying "match 0 or more space". If you want to match 0 or more of any character, you need .*.

ntpq -p | grep "10 L .* 64 377 0.000 0.000 0.001"

Although, you likely want to match "one or more of any character":

ntpq -p | grep -E "10 L .+ 64 377 0.000 0.000 0.001"

Even better, only match numbers or -:

ntpq -p | grep -E "10 L [[:digit:].\-]+ 64 377 0.000 0.000 0.001"

Upvotes: 5

Related Questions