[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: extract values from a string





On Sat, Apr 16, 2022 at 11:01 AM Nicholas Geovanis <nickgeovanis@gmail.com> wrote:
On Fri, Apr 15, 2022, 9:37 PM wilson <info@bigcount.xyz> wrote:
Hello

in shell script, how can I use regex to extract values from a string?
maybe value types transformation should be required.


for instance the string: "black berry 12".
I want go get the name: black berry [String]
the price: 12 [Int]


-- data.txt --
black berry 12
blue berry 14
raspberry 9
huckle berry hound 3
bare-knuckle sandwich 27

-- test.sh --
#!/bin/bash

file="data.txt"

while read -r line; do
   productID=$(awk -F' ' '{$NF=""; print $0}' <<< $line)
   price=$(awk -F' ' '{print $NF}' <<< $line)
   retail=$(($price * 2))
   printf "The price of \'$productID\' is \$$price. We will retail it for \$$retail.\n"
done <$file


-- $./test.sh --
The price of 'black berry ' is $12. We will retail it for $24.
The price of 'blue berry ' is $14. We will retail it for $28.
The price of 'raspberry ' is $9. We will retail it for $18.
The price of 'huckle berry hound ' is $3. We will retail it for $6.
The price of 'bare-knuckle sandwich ' is $27. We will retail it for $54.

--
Kent West                    <")))><
Westing Peacefully - http://kentwest.blogspot.com

Reply to: