Reputation: 195
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..
Upvotes: 1
Views: 1767
Reputation: 4043
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
Upvotes: 1
Reputation: 113814
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
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
Upvotes: 2