1

Consider I have a string and from that I need to extract particular keys values.

Example String : 17=TEST,90=BALANCE,45=SALARY,23=ULIP,20=PLAN,33=CREDIT,11=555

And consider if I wanted to get the value of 45 and 20 alone from the above string how can I get it ? one approach is to split based on ,(comma) and get it as an array and then search for the key and if it matches again split based on "=".

But is there any simple command to perform this task? thanks in advance..

0

2 Answers 2

2

POSIX

Let's define your string:

$ s='17=TEST,90=BALANCE,45=SALARY,23=ULIP,20=PLAN,33=CREDIT,11=555'

Now, let's extract the value for 45:

$ echo "$s" | awk -F= '$1==45{print $2}' RS=,
SALARY

And for 20:

$ echo "$s" | awk -F= '$1==20{print $2}' RS=,
PLAN

This works by using awk with a , as the record separator and = as the field separator. We select records whose first field is the value we want, in this case 45 or 20, and then print the second field.

To search the other way around:

$ echo "$s" | awk -F= '$2=="SALARY"{print $1}' RS=,
45

bash

If we are using bash, then we can use a here-string instead of a pipeline:

$ awk -F= '$1==20{print $2}' RS=, <<<"$s"
PLAN

Or:

$ awk -F= '$2=="PLAN"{print $1}' RS=, <<<"$s"
20
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the update..it's working as expected :) I had requirement with delimiter as "|" as well..that's also working if I modify RS='|' in the above commands.
1

Here's sed method to achieve your goal,

$ s="17=TEST,90=BALANCE,45=SALARY,23=ULIP,20=PLAN,33=CREDIT,11=555"
$ sed -E 's/.*,45=([A-Z]+),.*/\1/g' <<< "$s"
SALARY

$ sed -E 's/.*,20=([A-Z]+),.*/\1/g' <<< "$s"
PLAN

Or grep solution,

$ grep -oP '45=\K\w+' <<< "$s"
SALARY
$ grep -oP '20=\K\w+' <<< "$s"
PLAN

1 Comment

Thanks for the update..somehow the other delimiters are not flexible with the above commands.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.