Till now I have tried as below but no luck. Every time the line is appending to the file, even if the line is already present.
Note : there could be space or multiple tab between *.debug and @vxhgt-hskhng02. To handle the same I have used [:blank:] in my code.
PATTERN="*.debug[:blank:]@vxhgt-hskhng02" FILE=/etc/abc.conf if grep -q $PATTERN $FILE; then
echo "given pattern already found."
else
echo "pattern not found."
echo "*.debug @vxhgt-hskhng02" >> /etc/abc.conf
fi
kindly suggest where I am going wrong here.
---------- Post updated at 04:09 PM ---------- Previous update was at 03:35 PM ----------
After searching in google....I got something like below
if grep -Fxq $PATTERN $FILE;
then
echo "found"
else
echo "notfound"
fi
#!/bin/bash
PATTERN="\*\.debug[[:blank:]]*\@vxhgt-hskhng02"
myfile=/etc/testfile
if grep -q $PATTERN $myfile
then
echo "pattern found"
else
echo "not found"
fi
In the same code I just want to add a logic to append the entry to the file, if the entry is present but it is commented.
We dont want to change the whole script again and use awk command. I hope you can understand mine point of view. Would you mind to suggest a solution that use grep command.
It matches the pattern if preceded by only space ( [[:blank:]]* ) and only if that is at the beginning of the line ( ^ ). So if there is a comment character there, then there will be no match...
The old pattern that you were using wasn't right anyway, because if would have also matched something like tst*.debug @vxhgt-hskhng02 which is not right. Using ^[[:blank:]]* at the beginning fixes that as well (with the awk suggestion this precaution is not necessary since it uses string matching and discards leading space)..
Note that I removed the backslash before the @ since that is not necessary..
Thanks for your nice explanation and the way you handle and fix one more bug in my old logic. Appreciate your timely and quick response. I will have couple of tests again in our prod and will update thread.