1

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 \
3

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you know where the \K is mentioned in the manual / info pages? maybe this? perldoc.perl.org/perlre#Extended-Patterns (would have never guessed \K means that)
@ЯрославРахматуллин, Honestly I learnt it from Gurus in SO itself, after your comment I checked man pages and help but couldn't find it(at least in my grep version), but searching online I found this learnbyexample.gitbooks.io/command-line-text-processing/content/… site which has it. But doesn't look like it mentions too many details about it(though they have given few examples for it).
thanks. I modify it based on my needs and it is working
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.