Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to scan a text file for values that match some values that I obtain earlier. For clarity I'm statically assigning them here. The input file is a CSV but doesn't contain any commas. I'm open to using a plain text file if that helps.


QTY=157
ITEM="Housewares"

Logic:

Take 2 variables. Above, they were statically assigned. (ITEM & QTY)
Parse through file and IGNORE lines that match the current ITEM value.
For the remaining lines, display the lines that have same QTY

File contents:

           ITEM 	   SAMPLE  LOSS QTY	A 	CC DESCRIPTION
           Clothing 	Xxxx 	-92	157	Y  	-- 	WPA2(PSK/AES/AES) 
           Housewares	Yyyy 	-90	157	Y  	US 	NONE
           Automotive 	Zzzzz 	-89	48,-1   	Y  	-- 	WPA2(PSK/AES/AES) 
           Home repair	Aaaa 	-87	10,-1   	Y  	-- 	WPA2(PSK/AES/AES) 


What I have tried:

while read record
  do


    if [[ ! $record  =~ "${ITEM}" && $record =~ "${QTY}" ]]; then  
      read -ra ADDR <<< "$record"


      for i in "${ADDR[@]}"; do   # access each element of array
        echo "Possible matches: "${ADDR[@]}.  #display possible matches


        ITER=$(expr $ITER + 1)

      done

    else
        echo "Possible matches: ${green}0${reset}". #display 0 matches in green

        break

    fi
  done < scanlist.csv
Posted
Updated 24-Mar-21 4:20am
v2

1 solution

Problem one seems to be a mix of UTF-8 and ASCII quotation marks (") in your code -- assuming you did a cut&paste from your source.

Next, your logic is slightly off. You break the while loop and report no matches on the first non-match. One possible solution:
Shell
let ITER=0  #use bash integer math
while read record
do
    if [[ ! "$record"  =~ "${ITEM}" && "$record" =~ "${QTY}" ]]; then
       echo "posible match : $record"
       let ITER+=1
       #  process record as needed
    fi
done  < scanlist.csv

if [[ $ITER -eq 0 ]]; then
    echo "no matches found"
fi
Also note that this
Shell
for i in "${ADDR[@]}"; do   # access each element of array
  echo "Possible matches: "${ADDR[@]}.  #display possible matches
prints all items in the array for each array element, which is probably not what you want. Since i is an array element, not the index, you can manipulate the array element using $i. To access the array via an index, you can use i = ${!ADDR[@]}
 
Share this answer
 
Comments
wifinut 24-Mar-21 20:28pm    
Thank you so much for your help! That worked. The script was catching unwanted QTY characters that were part of other columns, so I added padding " " both before and after the QTY value and made that part of the IF condition and it now works perfectly!

Thanks again!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900