Rishab
Rishab

Reputation: 107

String Matching in Shell

I have file a file named as file.yaml with the below content :

SystemType=Secondary-HA
Hostname America

I have a shell script filter.sh:

echo "Enter systemType:"
read systemType
SYSTYPE=`grep systemType /home/oracle/file.yaml | awk '{print $2}'`
if [ SYSTYPE=Secondary-HA ]
then
    cat /home/oracle/file.yaml > /home/oracle/file2.txt
fi
hstname=`grep Hostname /home/oracle/file2.txt | awk '{print $2}'`
echo $hstname

Here I want to given the systemType only 'Secondary-HA' then only I should get the result as America. But as of now if I am giving the systemType 'Secondary', I am giving the same result as America. which I don't want. Please let know. I am bit new in shell scripting.

Upvotes: 0

Views: 54

Answers (1)

Jens
Jens

Reputation: 72629

You need to understand that the shell is white-space sensitive in certain places, for example when splitting arguments. Thus,

if [ x=y ]

must be written as

if [ x = y ]

In addition, I have replaced the anti-pattern

grep xyz file | awk '{print $2}'

with the much less expensive pipe-less

awk '/xyz/ {print $2}' file

Next, awk splits at white-space by default, not by =. You would need to say awk -F= to split at =. I have also uppercased systemType to SystemType, since that's what you tell us is in your yaml file. Mate, you need to be careful if you want to be in programming.

Here is the result:

echo "Enter systemType:"
read systemType
SYSTYPE=$(awk -F= '/SystemType/ {print $2}' /home/oracle/file.yaml)
if [ "$SYSTYPE" = "$systemType" ]; then
    cp /home/oracle/file.yaml /home/oracle/file2.txt
fi
hstname=$(awk '/Hostname/ {print $2}' /home/oracle/file2.txt)
echo $hstname

Upvotes: 1

Related Questions