Find values in string using awk

Viewed 196

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?

3 Answers

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.

How about a bash solution:

#!/bin/bash

x="Mobile:25:15000#TV:10:20000#Laptop:20:65000"
y="Laptop"
IFS=# read -r -a ary <<< "$x"           # split $x on "#" into array "ary"
for i in "${ary[@]}"; do                # loop over the elements of ary
    if [[ $i = $y* ]]; then             # if $y starts with an element
        echo "$i"                       # then print the element
    fi
done

Output:

Laptop:20:65000

With your shown samples, please try following awk code. Simple explanation would be, creating an awk variable named var which has value of bash variable y in it. In main program using match which has regex var":[^:]*:[^#]* in it, matching variable value will look till 2 values of colons till # is found and then printing matched value.

y="Laptop"
o_str=$(awk -v var="$y" 'match($0,var":[^:]*:[^#]*"){print substr($0,RSTART,RLENGTH)}' Input_file)

When we print variable output will be as follows:

echo "$o_str"
Laptop:20:65000
Related