Home > Back-end >  How to grep one string after pattern?
How to grep one string after pattern?

Time:12-02

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 \

CodePudding user response:

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.

CodePudding user response:

To get acc, you can also use awk here instead of grep:

awk '$1 == "yellow_y"{print $2}' file

This means: if the first word (first non-whitespace chunk) is yellow_y, return the second non-whitespace chunk of characters (the second word).

See an online demo:

#!/bin/bash
s='yellow      abc \
yellow_x     abc \
yellow_y      acc \
blue     abb \
pink abb \
pink_xx acd \'
awk '$1 == "yellow_y"{print $2}' <<< "$s"

Output is acc.

  • Related