I am trying to find a specific string from a file using grep with IF stmt. But I am not able to do so. The input file (filename: input_file_txt) carries a whole lot of string from which I am cutting down and taking only the values that are required to be searched on. I am doing using awk and writing it to file. Then, using grep, the string is searched. I end up with strange error which I am not able to figure it out. Giving the input file content, code I used and the error message I am getting
Content of input_file_txt :
123456 ----- abcd|abcd_vasa|nodatapts|1 ----- Assigned ----- @assignee ----- 0 ----- 2015-06-12
789011 ----- abcd|efgh_vasa|yesdata|56 ----- WIP ----- @assignee ----- 0 ----- 2015-06-12
And my code:
while
read LINE
echo "$LINE"
echo "going into the loop"
do
echo $LINE|awk -F\----- '{ print $2 }' >> /var/tmp/dummy_file
cat /var/tmp/dummy_file
if [ grep -q -i -E "abcd" /var/tmp/dummy_file ];then
count=expr "$count" + 1
echo "$count"
echo "$LINE" >> /var/tmp/dummy_ticket_NA
cat /var/tmp/dummy_ticket_NA
fi
done < /var/tmp/input_file_txt`
Error message I am getting is:
123456 ----- abcd|abcd_vasa|nodatapts|1 ----- Assigned ----- @assignee ----- 0 ----- 2015-06-12
going into the loop
abcd_vasa
going into the loop
going into the loop
going into the loop
going into the loop
going into the loop
Expected O/P is:
123456 ----- abcd|abcd_vasa|nodatapts|1 ----- Assigned ----- @assignee ----- 0 ----- 2015-06-12
going into the loop
abcd_vasa
1
abcd_vasa
@kojiro's link points to your issue, '[' is a command (the test command), not part of the syntax of an if statement.
The if statement you've written:
if [ grep -q "abcd" /var/tmp/dummy_file ];then
is equivalent to:
if test grep -q "abcd" /var/tmp/dummy_file ]; then
To use commands like grep in if statements just elide the brackets:
if grep -q "abcd" /var/tmp/dummy_file; then
...
fi
Setting -x
, -e
and -u
in your bash scripts, especially -x
when you're debugging them can be very valuable as it will print every statement that is executed in your script. '-e' will cause your script to exit on the first unsuccessful command (fail fast) and '-u' will case any use of an undeclared variable to be an error.
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.