Question

I am doing a update on the file test.txt which stores some info about storybooks

I've the code below for the function but i realise that using this method of grep, i am unable to get the rest of the values for price quantity and sold which are not mentioned in the grep command.

Is there a better command i can use for this case?

Thanks in advance for replies. :)

echo "Title: "
read title
echo ""
echo "Author: "
read author
echo ""
echo "Number of copies sold: "
read numSold

if grep -iq "$title:$author:" test.txt
then
echo "Current Book Info :"
echo "$title, $author, $price, $quantity, $sold"
echo ""

newQuantity=`expr $quantity - $numSold`
newSold=`expr $sold + $numSold`
sed -i "s/^\($title:$author:[^:]*\):[^:]*:/\1:$newQuantity:/" BookDB.txt 
sed -i "s/^\($title:$author:.*\):.*$/\1:$newSold/" BookDB.txt 


echo "New Book Info :"
echo "$title, $author, $price, $quantity, $sold"
fi
Was it helpful?

Solution

Well unfortunately the build of the test.txt is unknow. If you could show an example that can help.

But if the Price quantity and other staff are in the 1-2 line away from the line you grepping you can use the grep -A 2 (which will grep 2 next lines) or -B 2 (2 lines from above) after that u can just remove the '\n'from the results and print it :

grep -A 2 "$title:$author:*" | tr '\n' ' ' 

this will give you a line (build out of 3 lines) with all the data. Of course its based on the how test.txt is build.

some thing like this :

> grep -A 2 "Konan Doil:Story" test.txt
Konan Doil:Story
Price - $$$$$
Quantity - XXXX, Sold - 99999

In response to the comment below : I think its better then use array to save the input. after that u can do with array what ever you want as the values are same (Index 0 = Author, 1 = Book Name ... etc.)

 >IFS=$':'; i=0 ; for line in $(grep "Konan Doil:Good" test.txt) ; do arr[$i]=$line; i=$(($i + 1)) ; done
 >echo "${arr[0]}"
Konan Doil
>echo "${arr[1]}"
Good story
 >echo "${arr[3]}"
XXXXX
 >echo "${arr[4]}"
YYYYYY
 >echo "${arr[2]}"
$$$$$
 >
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top