Friday, March 18, 2022

[SOLVED] Find values in string using awk

Issue

I am new to shell scripting. I am trying pick all the fields value from string if it matches with the another string. For example i have a string like

Mobile:25:15000#TV:10:20000#Laptop:20:65000

and another string is TV then my code should pick data from TV:10:20000 same if the another string is Mobile then it should pick Mobile:25:15000.

The code so far I have written is as below:

#!/bin/bash
x="Mobile:25:15000#TV:10:20000#Laptop:20:65000"
y="Laptop"
o_str=$(echo "$x"| awk -F "#" 'BEGIN{OFS="\n"} {if ($1== $y) print } y=$y');
echo $o_str

I know I am doing something wrong but cant able to figure it out. Can someone tell me where am I going wrong?


Solution

You can use

o_str=$(awk -v y="$y" -F: 'BEGIN{RS="#"} $1 == y' <<< "$x");

See the online demo:

#!/bin/bash
x="Mobile:25:15000#TV:10:20000#Laptop:20:65000"
y="Laptop"
o_str=$(awk -v y="$y" -F: 'BEGIN{RS="#"} $1 == y' <<< "$x");
echo "$o_str"
## => Laptop:20:65000

Details:

  • -v y="$y" - pass tje y variable to awk script
  • -F: - the field separator is set to a : char
  • BEGIN{RS="#"} - record separator is set to a # char
  • $1 == y - if Field 1 value is equal to y variable value, print this record.


Answered By - Wiktor Stribiżew
Answer Checked By - David Marino (WPSolving Volunteer)