Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Grep Print Only After Match [duplicate]

Writer Matthew Harrington

I used grep that outputs a list like this

/player/ABc12
/player/ABC321
/player/EGF987
/player/egf751

However I want to only give the name of the players such ABC321, EFG987, etc...

1

4 Answers

Start using grep :

$ grep -oP "/player/\K.*" FILE
ABc12
ABC321
EGF987
egf751

Or shorter :

$ grep -oP "[^/]/\K.*" FILE
ABc12
ABC321
EGF987
egf751

Or without -P (pcre) option :

$ grep -o '[^/]\+$' FILE
ABc12
ABC321
EGF987
egf751

Or with pure bash :

$ IFS=/ oIFS=$IFS
$ while read a b c; do echo $c; done < FILE
ABc12
ABC321
EGF987
egf751
$ IFS=$oIFS
1

@sputnick has the right idea with grep, and something like that would actually be my preferred solution. I personally immediately thought of a positive lookbehind:

grep -oP '(?<=/player/)\w+' file

But the \K works perfectly fine as well.

An alternative (somewhat shorter) solution is with sed:

sed 's:.*/::' file
1

Stop using grep.

$ awk -F/ '$2 == "player" { print $3 }' input.txt
ABc12
ABC321
EGF987
egf751

One way using GNU grep and a positive lookbehind:

grep -oP '(?<=^/player/).*' file.txt

Results:

ABc12
ABC321
EGF987
egf751