user2519184
user2519184

Reputation: 67

Search for exact string

I'm trying to search for exact string located in chars number 4-7. When I run the cut command on terminal it works, however in a script it fails as I believe the if statement provide me "0". This is what I've done:

for NAME in `cat LISTS_NAME`; do
if [[ John == cut -c 4-7 "${NAME}" ]]; then 
   Do Something ...
fi
if [[ Dana == cut -c 4-7 "${NAME}" ]]; then 
  Do Something... 
fi

Can you advise me how to run this using cut or any other reg-ex?

Upvotes: 0

Views: 102

Answers (2)

anubhava
anubhava

Reputation: 785098

Your script has many problems and you don't need cut. Use it this way:

while read -r line; do
   if [[ "${line:3:4}" == "John" ]]; then 
      Do Something ...
   elif [[ "${line:3:4}" == "Dana" ]]; then 
     Do Something... 
   fi
done < LISTS_NAME

In BASH "${line:3:3}" is same as cut -c 4-7


EDIT: If you don't want precise string matching then you can use:

while read -r line; do
   if [[ "${line:3}" == "John"* ]]; then 
      Do Something ...
   elif [[ "${line:3}" == "Dana"* ]]; then 
     Do Something... 
   fi
done < LISTS_NAME

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 80931

You aren't running the cut command there. You are comparing John and Dana to the literal string cut -c 4-7 <value-of-$NAME>.

You need to use:

if [[ John == $(cut -c 4-7 "${NAME}") ]]; then

etc.

That being said you should only do the cut call once and store that in a variable. And for exact matching you need to quote the right-hand side of == to avoid globbing. So

substr=$(cut -c 4-7 "${NAME}")
if [[ John == "$substr" ]]; then

And then to avoid needing duplicate if ...; then lines you could do better with a case statement:

substr=$(cut -c 4-7 "${NAME}")
case $substr in
    John)
         Do something
    ;;
    Dana)
         Do something else
    ;;
esac

Upvotes: 1

Related Questions