How to grep one string after pattern?

Advertisements

I would like to get the string from the file after user defined keyword. Example if keyword is "yellow_y", expected output to be acc.

Tried grep -oP '(?<=yellow_y).*' but not work.

File:

yellow      abc \
yellow_x     abc \
yellow_y      acc \
blue     abb \
pink abb \
pink_xx acd \

>Solution :

With your shown samples, please try following grep command. Written and tested in GNU grep.

grep -oP '^yellow_y\s+\K\S+'  Input_file

Online demo for above regex

Explanation: Simple explanation would be, using -oP options of GNU grep which is for printing matched words and enabling PCRE regex respectively. In main program using regex to match condition. Checking if line starts from yellow_y followed by 1 or more spaces then using \K capability of GNU grep to forget this match and matching 1 or more non-spaces characters then which will provide required values in output.

Leave a ReplyCancel reply