Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using awk to retrieve a specific set of strings from a file

textFileA consists of:

mango:oval:yellow:18pcs
apple:irregular:red:12pcs
orange:round:orange:4pcs

I wanted to do something like allowing user input for example user search "mango"
I want the system to print out

Please enter the fruit name : mango >> this is user input

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desire Output

Fruit Shape : Oval
Fruit Color : Yellow
Fruit Quantity : 18pcs

So far this is what i done and it could only print out the entire line of strings, did i do something wrong here?

echo -n "Please enter the fruit name :"
read fruitName
awk '/'$fruitName'/ {print}'  textFileA

Current Output

mango:oval:yellow:18pcs

>Solution :

You may use it like this:

read -p "Please enter the fruit name: " fruitName
awk -F: -v fruitName="$fruitName" '
$1 == fruitName {
   print "Fruit Shape :", $2
   print "Fruit Color :", $3
   print "Fruit Quantity :", $4
}' file

Output:

Please enter the fruit name: mango
Fruit Shape : oval
Fruit Color : yellow
Fruit Quantity : 18pcs
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading