Comparing strings with special characters using if-loop does not work

5,792

Solution 1

Most simple method is to use single quotes on the right hand side:

if [ "$line" == '#orb_plugins = ["local_log_stream", "iiop_profile", "giop", "iiop"];' ]

This way the string to be matched is interpreted literally.

If you prefer using double quotes, you must not escape the brackets ([]), but only the double quotes (""):

if [ "$line" == "#orb_plugins = [\"local_log_stream\", \"iiop_profile\", \"giop\", \"iiop\"];" ]

Solution 2

Why not using the right tool for this job, i.e. grep:

grep -qxFf- file.txt <<\IN && printf %s\\n "String found. Do remaining steps"
#orb_plugins = ["local_log_stream", "iiop_profile", "giop", "iiop"];
IN

This stops reading the file as soon as a match is found. It's also (on average) about 100 times faster than your while read loop.

Share:
5,792

Related videos on Youtube

Anusuya Nandi
Author by

Anusuya Nandi

Updated on September 18, 2022

Comments

  • Anusuya Nandi
    Anusuya Nandi almost 2 years

    I want to compare each line of a particular file with the following string

    #orb_plugins = ["local_log_stream", "iiop_profile", "giop", "iiop"];
    

    ("file.txt" contains this particular line)

    I tried the following by prefixing special characters with '\'

    IFS=''
    while read -r line
    do
      if [ "$line" == "#orb_plugins = \[\"local_log_stream\", \"iiop_profile\", \"giop\", \"iiop\"\];" ]
      then
        echo "String found. Do remaining steps"
      fi
    done < file.txt
    
    • Rui F Ribeiro
      Rui F Ribeiro over 8 years
      You are trying to define an array there, but then you do not use it, I think. Would not be easier to use a case statement?
  • Anusuya Nandi
    Anusuya Nandi over 8 years
    Thanks for the tip. This is just part of my 100 line code. I am not skilled enough to use grep/sed instead of using grep in all places. As you mentioned, the script runs too slow.
  • Anusuya Nandi
    Anusuya Nandi over 8 years
    Using single quotes solves the problem. Thank you