0

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.

2
  • 2
    Ok, for one, take a look at the editing help, and the first item about code block formatting. Use that for scripts and data files: it helps the reader to see exactly what there is in the file. Also, do check the syntax of your script, use something like [shellcheck.net](shellcheck.net) for that. If you have syntax errors in your script, it distracts from the main issue, and makes it harder for the readers to help you. Also, the historical-unix tag is for the actually historical 70's and 80's UNIX, probably not what you're using
    – ilkkachu
    Aug 24 at 20:31
  • How are the values in the "names" variable separated? Which scripting language/shell are you using?
    – sborsky
    Aug 24 at 20:58
1

I formatted your question, including your pseudocode , but the way you are attempting to do this will not work. Your $names variable is not an array, but a single long string with line breaks included. This is how you can iterate over such a string in the future.

This is our sample names.txt file we will grep over to simulate the process

###                 names.txt                  ###
### our sample file to grep over as an example ###
##################################################
Abc xyz
Pqr def
Lmn ghi

with the code being the following:


names=$(grep -v '^#' names.txt)

i=1;
while read n; do 
  echo "Name $i. $n"
  if [[ "$n" == "Pqr def" ]]; then
      echo "--- $n was found at line $i"
  fi    
  i=$(($i+1)); 
done <<< "$names"

Your output will look like this:

Name 1. Abc xyz
Name 2. Pqr def
--- Pqr def was found on line 2
Name 3. Lmn ghi
0

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.