How to remove a word prefix using grep?

Viewed 48064

How can I remove the beginning of a word using grep ? Ex: I have a file that contains:

www.abc.com

I only need the part

abc.com

Sorry for the basic question. But have no experience with Linux.

6 Answers

with grep's --only-matching and \K

You can do this with a grep's --only-matching flag:

echo "www.abc.com" | grep --perl-regexp --only-matching 'www.\K.*'

which can be shortened to

echo "www.abc.com" | grep -Po 'www.\K.*'

Both commands produce

abc.com

with grep (GNU grep) 3.3.

Instead of echo, I'll use a here string to shorten the command further:

grep -Po 'www.\K.*' <<< "www.abc.com"

\K resets the starting point of the match, essentially forgetting the matched "www.". See this for more on \K.

with grep's positive lookbehind

You can also do this with a positive lookbehind:

grep -Po '(?<=www.).*' <<< "www.abc.com"

with awk's field separator -F

awk -F 'www.' <<< "www.abc.com" '$2{print $2}'

This prints

abc.com

The $2{print $2} part will print the second field if it's defined. This is necessary in case of multi-line input to avoid outputting blank lines for input lines that don't contain the field separator.

Related