Grep and Cut – How to Use Grep and Cut Together

cutdatabasegrep

Lets say I'm doing a database for fruits.
Using a text file for it, inside contains, in this format,

(Fruit:Quantity:Cost)
Apple:10:1
Orange:20:2
Pears:10:3
Banana:20:4

10 Apples at $1 each.
20 Oranges at $2 each.
10 Pears at $3 each.
20 Bananas at $4 each.

My simple script goes like this:

echo "Enter fruit to find"
read fruit

echo "Enter quantity to find"
read count

echo "Enter cost to find"
read cost

grep $fruit FruitDB.txt

It will display the fruits in the database.

But how do i use grep and cut together to find just by the quantity or the cost. In the quantity count area, let's say i enter 20, it will display the Oranges and Banana. Or when i enter count and cost, it will display just those that meet the conditions.

Best Answer

You don't need cut at all, just bare grep is enough in the form:

grep "^$fruit:$count:$cost$" FruitDB.txt

Remove any variable you don't want to grep at the time (but leave separators :, and begining and end of line signs ^ and $ (for edge variables)).

For example to grep those with count=20:

$ grep ":$count:" FruitDB.txt
Orange:20:2
Banana:20:4

grep those with count=20 and cost=2:

$ grep ":$count:$cost$" FruitDB.txt
Orange:20:2
Related Question