Searching for values in a file

Hi guys.

I'm trying to do a search on the fruit & brand inside Fruit.txt, and printing the result out in the following format:

[fruit], [brand], $[price], [qty]

I am able to do this via the following code:

awk -F: -vOFS=", " -vt="$Fruit:$Brand" '$0~t{$3="$"$3;print}' Fruit.txt

However, I want to be able to search only one word anywhere on the string (case insensitive), and it will still be able to return me the results.

Example as follows:

Enter fruit name: sour
Enter brand: [null]

Found 2 matches:
Sour Grapes, Sunshine Ltd, $0.95, 200
Sour Apples, Moonlight Ltd, $0.30, 100

---------------------------------------
Enter fruit name: sour
Enter brand: moonlight

Found 1 match:
Sour Apples, Moonlight Ltd, $0.30, 100

How do I go about putting the search conditions?

The easiest way might be to make the t variable a regex: -vt="$Fruit.*$Brand" It will find the lines with both strings present (Fruit before Brand!), or, if one is missing, all the lines having the other value.

1 Like

Sorry, I haven't tried the code yet, but if let's say I were to find "Apples", will I be able to get back:

Surprising question. Just try! I'm pretty confident it will.

1 Like

I tried the code. It seems to be able to work.

However, I just tried to search in lowercase, but it didn't return any results.

Also, if one search term is missing, but the other is present, the result will be "Please fill in the necessary information.".

if test "$Fruit" = "" || test "$Brand" = ""; then
			echo "Please fill in the necessary information."
		else
			awk -F: -vOFS=", " -vt="$Fruit.*$Brand" '$0~t{$3="$"$3;print}' Fruit.txt
		fi

awk works case sensitively. If you want to match upper and lower case chars, special action has to be taken, like applying the toupper/tolower functions. Or modify the regex accordingly (hint: [aA]).