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


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
    Usually such cases would be handled with awk. Is grep a requirement? – Hauke Laging Jan 8 '15 at 15:49

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

grep those with count=20 and cost=2:

$ grep ":$count:$cost$" FruitDB.txt
|improve this answer|||||
  • You may prefer grep -xFe "$fruit:$count:$cost" in case those variables contain regexp operators (for instance . in $cost). – Stéphane Chazelas Jan 8 '15 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.