0

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.

1
  • 1
    Usually such cases would be handled with awk. Is grep a requirement? Commented Jan 8, 2015 at 15:49

1 Answer 1

1

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
1
  • You may prefer grep -xFe "$fruit:$count:$cost" in case those variables contain regexp operators (for instance . in $cost). Commented Jan 8, 2015 at 15:56

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.