XYZ_Linux
XYZ_Linux

Reputation: 3597

how to extract string appears after one particular string in Shell

I am working on a script where I am grepping lines that contains -abc_1. I need to extract string that appear just after this string as follow :

option : -abc_1 <some_path>

I have used following code :

grep "abc_1" | awk -F " " {print $4}

This code is failing if there are more spaces used between string , e.g :

   option :   -abc_1 <some_path>

It will be helpful if I can extract the path somehow without bothering of spaces. thanks

Upvotes: 0

Views: 89

Answers (4)

Jotne
Jotne

Reputation: 41446

This should do:

echo 'option :   -abc_1 <some_path>' | awk  '/abc_1/ {print $4}'
<some_path>

If you do not specify field separator, it uses one ore more blank as separator.
PS you do not need both grep and awk

Upvotes: 2

Kent
Kent

Reputation: 195029

try this grep only way:

grep -Po '^option\s*:\s*-abc_1\s*\K.*' file

or if the white spaces were fixed:

grep -Po '^option : -abc_1 \K.*' file

Upvotes: 0

Vijay
Vijay

Reputation: 67211

perl -lne ' print $1 if(/-abc_1 (.*)/)' your_file

Tested Here Or if you want to use awk:

awk '{for(i=1;i<=NF;i++)if($i="-abc_1")print $(i+1)}' your_file

Upvotes: 0

SzG
SzG

Reputation: 12609

With sed you can do the search and the filter in one step:

sed -n 's/^.*abc_1 *: *\([^ ]*\).*$/\1/p'

The -n option suppresses printing, but the p command at the end still prints if a successful substitution was made.

Upvotes: 0

Related Questions