Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating data text file with bash command?

Tags:

bash

I was given this text file, call stock.txt, the content of the text file is:

pepsi;drinks;3
fries;snacks;6
apple;fruits;9
baron;drinks;7
orange;fruits;2
chips;snacks;8

I will need to use bash-script to come up this output:

Total amount for drinks: 10
Total amount for snacks: 14
Total amount for fruits: 11
Total of everything: 35

My gut tells me I will need to use sed, group, grep and something else.
Where should I start?

like image 352
bashington02 Avatar asked Nov 15 '22 05:11

bashington02


2 Answers

I would break the exercise down into steps

Step 1: Read the file one line at a time

while read -r line
do
    # do something with $line
done

Step 2: Pattern match (drinks, snacks, fruits) and do some simple arithmetic. This step requires that you tokenized each line which I'll leave an exercise for you to figure out.

if [[ "$line" =~ "drinks" ]]
then
    echo "matched drinks"
    .
    .
    .
fi 
like image 74
Amir Afghani Avatar answered Dec 28 '22 09:12

Amir Afghani


Pure Bash. A nice application for an associative array:

declare -A category                  # associative array
IFS=';'
while read name cate price ; do
  ((category[$cate]+=price))
done < stock.txt

sum=0
for cate in ${!category[@]}; do       # loop over the indices
  printf "Total amount of %s: %d\n" $cate ${category[$cate]}
  ((sum+=${category[$cate]}))
done

printf "Total amount of everything: %d\n" $sum
like image 21
Fritz G. Mehner Avatar answered Dec 28 '22 09:12

Fritz G. Mehner