Chudar Chudar - 1 month ago 8
Linux Question

If-conditionw with "+" and "-" symbol in bash

I and new to bash scripting and have tab-delimted text file with following columns

A234 + -
B654 - +
C630 + +
D707 - -


I would like to compare traverse every line of a file and compare second and third column to get an output like following in a text file

A234 Plus and Minus
B654 Minus and Plus
C630 Plus and Plus
D707 Minus and Minus


here is my bash script

#!/bin/bash
filename="$1"
while read line;
do
g_symbol=$(echo $line | awk '{print $2}')
t_symbol=$(echo $line | awk '{print $3}')
if [[($g_symbol == "+") && ($t_symbol == "-")]]
then
echo $filename "PLus and Minus"
elif [[($g_symbol == "-") && ($t_symbol == "-")]]
then
echo $filename "Minus and Minus"
elif [[($g_symbol == "-") && ($t_symbol == "+")]]
then
echo $filename "Minus and Plus"
else
echo $filname "Plus and Plus"
fi
done < "$filename"


But when I execute it, I get the following error

[[(+: command not found
[[(-: command not found
[[(-: command not found
[[(+: command not found


Kindly guide me.

Answer

It is easier to do using awk:

awk 'BEGIN{a["+"]="Plus"; a["-"]="Minus"} {print $1, a[$2], "and", a[$3]}' file

A234 Plus and Minus
B654 Minus and Plus
C630 Plus and Plus
D707 Minus and Minus