Skip to main content
5 of 5
formatting and tags
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

How to loop over grep command results and check condition for each value inside the loop?

So I have a file which has some person's full names (first name and last name) in it on various seperate lines which starts with some specific pattern. With the help of grep command I have succeeded in extracting only the full names and storing it in variable. Now I need to access every full name and check if it matches with some value from another variable. I tried using for loop but it treats first name and last name as seperate items because they have space in between. I need to get first and last name together and check it with other variable.

Eg. After running grep command I get 3 values and are stored in variable names.

Abc xyz
Pqr def
Lmn ghi

Running the for loop as below:

for n in $names; do
 echo $n
   if [ "$n" = "Abc Pqr" ]; then
    echo "something"
   fi
done

Gives following output:

Abc
xyz
Pqr
def
Lmn
ghi

I want $n to have both Abc xyz (first name and last name) together so that I can check the condition.

Harry367
  • 11
  • 1
  • 1
  • 2