Bosti Andrei
Bosti Andrei

Reputation: 47

Ubuntu grep that will show a word pattern and assign to variable

I am trying to do a grep to print a text patern (usr1234) for a directory. The best I could do so far is save the filename and line were the word is found. usr1234 can have 3 digits or 4: usr123 or usr1234

This is my current grep:

usrcode=$(grep -oPnr 'usr[0-9][0-9][0-9][0-9]' filename)

and the result is:

filename/filelocation/file:7:usr1234 filename/filelocation2/file2:8:usr1234 filename/filelocation3/file3:7:usr1234

all I need is to store usr1234(or usr123 depending on the case)

Upvotes: 0

Views: 62

Answers (2)

Bosti Andrei
Bosti Andrei

Reputation: 47

The lucky one:

usrcode=$(grep -ohr 'usr[0-9][0-9][0-9][0-9]' filename  | head -1)

Upvotes: 1

Filip
Filip

Reputation: 128

Pipe it do sed:

sed 's/\(.*\)\(usr[0-9]*\)/\2/'

Like this:

usrcode=$(grep -oPnr 'usr[0-9][0-9][0-9][0-9]' filename | sed 's/\(.*\)\(usr[0-9]*\)/\2/')

Upvotes: 0

Related Questions