1

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!

cHao
  • 84,970
  • 20
  • 145
  • 172
Motorahead
  • 75
  • 1
  • 6

1 Answers1

5

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"
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • Your a life saver.. The ,* worked perfectly. I tried [[:digit:].-]+ and couldnt get it to work for some reason, but no worries. – Motorahead Aug 17 '12 at 18:50
  • @36DDJuicer - I updated the answer. It's because - is special inside of a character class and must be escaped. If you found the answer helpful, you should "accept" it. – jordanm Aug 17 '12 at 19:15
  • Why would they break the most common convention? I don't see any reason to other than to make it more complicated and less familiar to the average user. – Philip Rego Aug 23 '21 at 15:55