Reputation: 307
Part of a script I'm writing needs to check various text files for the same strings. Before I just had to check one file so I had a long list of strings within cateogies to search for which are defined as variables. Later on in the script the variabled are called and output to the screen if there is a match:
category_1=$(sudo zcat myfile | egrep -c 'Event 1|Event 2|Event 3')
category_2=$(sudo zcat myfile | egrep -c 'Event 4|Event 5|Event 6')
category_3=$(sudo zcat myfile | egrep -c 'Event 7|Event 8|Event 9')
...
echo Category 1
if [[ $category_1 -ge 2 ]];then
echo There were $category_1 events
elif [[ $category_1 -eq 1 ]]; then
echo There was $category_1 event
fi
etc, etc...
Now I need to change it so that I can check the grepped strings against multiple text files. I've tried to define the new files as variables and pipe them in the if statement with the grep variable to no avail:
category_1=$(egrep -c 'Event 1|Event 2|Event 3')
category_2=$(egrep -c 'Event 4|Event 5|Event 6')
category_3=$(egrep -c 'Event 7|Event 8|Event 9')
myfile=$(sudo zcat myfile)
myfile2=$(sudo zcat myfile2)
myfile3=$(sudo zcat myfile3)
...
echo Category 1 - Myfile
if [[ myfile | $category_1 -ge 2 ]];then
echo There were $category_1 events in myfile
elif [[ myfile | $category_1 -eq 1 ]]; then
echo There was $category_1 event in myfile
fi
It seems that I can't pipe commands in an if statement.
Upvotes: 18
Views: 35918
Reputation: 1
You could instead use a command such as: if [ "$house" = "nice" ]||[ "$house" = "bad" ] then... to do the job
Upvotes: 0
Reputation: 64563
You can use pipes in if
, but you mix two things.
You use $category_1
with pipe; and $category_1
is not a command.
You can use a command substitution instead of the variable.
if [[ `sudo zcat myfile | egrep -c 'Event 1|Event 2|Event 3')` -ge 2 ]];then
and so on.
You can also use variables instead of commands, but it will be a little bit strange.
Upvotes: 1
Reputation: 241838
Use $(...)
to capture output of a command into a string:
if [[ $(sudo zcat myfile1 | egrep -c 'Event 1|Event 2|Event 3') -ge 2 ]] ; then
Upvotes: 25