kiran k
kiran k

Reputation: 41

parsing key value in shell script

I have a file and want to look for value from that file using shell script.

So I'm trying to grep value using the below code.

VAR=($grep -Po "(?source-no": ")(\d+)" file)

but it's giving an error

grep missing )

Data in the file looks like below

"source-no" : "123456",

Upvotes: 2

Views: 751

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133468

1st solution: Considering that you need to get digits as output, you could try following then. You are on right path, you need to fix 2 things here: correct your matching regex, where in look behind you need to fix " in it. Then to save it into shell variable: use grep command inside $(grep command) in this form.

grep -oP '(?<="source-no" : ")(\d+)' Input_file

To save this into a variable try following:

var=$(grep -oP '(?<="source-no" : ")(\d+)' Input_file)

Also try to keep shell variables name with small letters, which is recommended by experts IMHO.


2nd solution:

grep -oP '(?<= ")[\w\.]+(?=")' Input_file

(?<= ") match the pattern begin with, as (?=") match the pattern end with,[\w\d\.]+ match the value you need that consist by word or digital or dot(.) which I guess the value pattern.


3rd solution: OR using both positive lookahead and positive lookbehind here:

grep -oP '(?<="source-no" : ")\d+(?=")' Input_file

Upvotes: 3

The fourth bird
The fourth bird

Reputation: 163287

As already mentioned in the comments, using $grep is variable expansion.

Note that this part of the pattern (?source-no": ") is not a valid pattern, and it is also missing a space before the colon.

As you are using -P for Perl-compatible regular expressions, you can make use of \K to clean the current match buffer.

"source-no" : "\K\d+(?=")
  • "source-no" : " Match literally
  • \K Forget what is matched so far
  • \d+(?=") Match 1+ digits and assert " directly to the right

For example

VAR=$(grep -Po '"source-no" : "\K\d+(?=")' file)
echo $VAR

Output

123456

Upvotes: 2

Related Questions