Reputation: 684
Here's my code. It's basically just grep'ing and making the output look nicer. It works just fine, however if I use REGEX input the output is blank. The "myVar" which counts the # of grep lines returned seems to be correct, but it seems like awk is losing the output text.
Thanks.
#!/bin/bash
center() {
termwidth="$(tput cols)"
padding="$(printf '%0.1s' ={1..500})"
printf '%*.*s %s %*.*s\n' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding"
}
if [ $1 = "-h" ] || [ $# -eq 0 ]; then
echo 'USAGE: ./Check.sh [PATTERN1] [PATTERN2] [PATTERN3] ... [PATTERN20]
Search for PATTERN in the HOSTS file. Patterns can be in the Perl REGEX form.'
else
for item in "$@"
do
center "SEARCHING $item"
grep -i $item /etc/hosts
myVar=$(wc -l <(grep -i -P $item /etc/hosts) | awk '{print $1}')
if [ $myVar -eq 0 ]; then
center "COULD NOT FIND $item"
fi
center "FOUND $myVar IN $item"
done
fi
OUTPUT:
$ ./Check.sh '^142.[0-9]+'
=================================================================== SEARCHING ^142.[0-9]+ ===================================================================
================================================================= FOUND 945 IN ^142.[0-9]+ ==================================================================
$ cat /etc/hosts | grep -i -P -c '^142.[0-9]+'
945
If I input a non-regex string the output and count are both fine. The file being grep'ed is a corporate host file so I can't share successful output, but basically the matched lines go between the "SEARCHING" and "FOUND" line.
Upvotes: 0
Views: 52
Reputation: 295345
It's not that content from the first grep
is being dropped somehow (which is impossible without terminal control characters clearing the screen or moving the cursor upwards, as that output was already sent to the terminal before awk
is started). Rather, the second grep
is being run with different arguments, such that only the grep
whose output goes to wc -l
and then to awk
is parsing its argument as a PCRE-style regex at all.
Change:
grep -i $item /etc/hosts
To:
grep -i -P "$item" /etc/hosts
Upvotes: 1