简体   繁体   中英

Compare strings in shell script

I have a file named parameters.txt whose contents are as follows:

sheet_name:TEST
sheet_id:CST
sheet_access:YES

And I have a shell script which fetches this text from the parameters.txt file. It uses : as a delimiter for each line of the parameters.txt file and stores whatever is left of : in var1 and whatever is right of : in var2 . I want to print matched when var1 stores sheet_name and not matched when it doesn't stores sheet_name . Following is my code which always prints matched irrespective of what var1 stores:

filename=parameters.txt
IFS=$'\n'       # make newlines the only separator

for j in `cat $filename`
   do
      var1=${j%:*} # stores text before :
      var2=${j#*:} # stores text after :

      if [ “$var1” == “sheet_name” ]; then
         echo ‘matched’
      else
         echo “not matched“
      fi

done

What am I doing wrong? Kindly help.

You have useless use of cat. But how about some [ shell parameter expansion ] ?

while read line
do
 if [[ "${line%:*}" = "sheet_name" ]] #double quote variables deals word splitting
 then
  echo "matched"
 fi
done<parameters.txt

would do exactly what you're looking for.


Message for you

[ ShellCheck ] says,

"To read lines rather than words, pipe/redirect to a 'while read' loop."


Check [ this ] note from shellcheck.

How about this?

filename=parameters.txt

while IFS=: read -r first second; do 
  if [ “$first” == “sheet_name” ]; then 
     echo ‘matched’
  else  
     echo “not matched“ 
  fi 
done < $filename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM