Photon Light
Photon Light

Reputation: 777

Match string and one or more numbers with grep

I've got a file myfile. I want to find lines that includes following pattern:

MyWebsite/1234

or more general

somecharactersstringswhitespacesMyWebsite/987somecharactersstringswhitespaces

There can be 1 or more numbers after MyWebsite. I have tried following:

grep ".*MyWebsite[0-9]\{1,\}" myfile
grep "MyWebsite[0-9]\{1,\}" myfile
grep MyWebsite"[0-9]\{1,\}" myfile
grep -E ".*MyWebsite/[0-9]\{1,\}.*" myfile

None of them worked, even if intuition and logic says that should be good.

Upvotes: 4

Views: 8835

Answers (2)

Jimmix
Jimmix

Reputation: 6546

Setup

grep (GNU grep) 3.7

Solution

grep 'MyWebsite/[[:digit:]]\+' myfile

Breakdown

  • [[:digit:]] character class that matches digits 0..9
  • \ escape character
  • + match one or more characters (digits in this case)

Prove

# create myfile with content 'a bc/MyWebsite/1234/d ef'
echo 'a bc/MyWebsite/1234/d ef' > myfile

# test grep
grep 'MyWebsite/[[:digit:]]\+' myfile

# remove myfile
rm myfile

Result

a bc/MyWebsite/1234/d ef

Highlighted pattern match

enter image description here

Links

Upvotes: 1

squirl
squirl

Reputation: 1784

grep 'MyWebsite/[0-9]\+' myfile should work. On your first 3 regexes, you missed the / and on the last, you shouldn't have escaped the { and }, but otherwise you were pretty good. It's more concise to use + rather than {1,} though, and the version of regex that grep uses by default (a variant of POSIX BRE) requires it to be escaped.

Upvotes: 4

Related Questions