isme
isme

Reputation: 190

How to cut a variable to sub variable

I have a variable which store consist of

TITLE:AUTHOR:PRICE:QUANTITY:SOLDQUANTITY

in this case its

wrinkle in time:myauthor:50.00:20:50

I store it in

Result=`awk -F : -v "Title=$1" -v "Author=$2" 'tolower($1) == tolower(Title) && tolower($2) == tolower(Author)' BookDB.txt`

however I would like to separate it into 4 variables like

TITLE= "wrinkle in time"
AUTHOR= "myauthor"
PRICE= "50.00"
Quantity= "20"
UNIT= "50"

then I would like to do a calculation for unit sold

enter unit sold: 3

wrinkle in time, myauthor, 50.00, 20, 50

after update

wrinkle in time, myauthor, 50.00, 17, 53

thanks in advance your help is much appreciated!!!

Upvotes: 1

Views: 59

Answers (1)

Josh Jolly
Josh Jolly

Reputation: 11796

You can separate $result into the different variables you describe by using read:

IFS=: read TITLE AUTHOR PRICE QUANTITY UNIT <<< "$result"

Example:

$ result="wrinkle in time:myauthor:50.00:20:50"
$ IFS=: read TITLE AUTHOR PRICE QUANTITY UNIT <<< "$result"
$ echo "$TITLE - by - $AUTHOR"
wrinkle in time - by - myauthor

You can also use read to prompt a user for input:

read -p "Enter units sold: " SOLDUNITS

This will store the value entered in the variable $SOLDUNITS. You can then use this to alter $QUANTITY and $UNIT as desired. To do (integer) arithmetic in bash, you can use the $((expression)) construct:

QUANTITY=$((QUANTITY-SOLDUNITS)) 

Or:

((QUANTITY-=SOLDUNITS))

Upvotes: 2

Related Questions