Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string and one or more numbers with grep

Tags:

regex

linux

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.

like image 478
Photon Light Avatar asked Oct 14 '25 08:10

Photon Light


2 Answers

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.

like image 70
squirl Avatar answered Oct 16 '25 22:10

squirl


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

  • grep Character Classes and Bracket Expressions
like image 30
Jimmix Avatar answered Oct 16 '25 22:10

Jimmix