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?
CodePudding user response:
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 tjeyvariable toawkscript-F:- the field separator is set to a:charBEGIN{RS="#"}- record separator is set to a#char$1 == y- if Field 1 value is equal toyvariable value, print this record.
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
Block-level HTML elements have a few restrictions:
They must be separated from surrounding text by blank lines. The begin and end tags of the outermost block element must not be indented. Markdown can't be used within HTML blocks.
Best Regards Tech2toward
