I'm having trouble storing a grep result as a variable in a loop.
while read file;do
Server=$(echo $file | awk '{ print $1 }')
FDate=$(echo $file | awk '{ print $2 }')
ST=$(cat foobar | grep $Server | awk '{ print $3 }')
#ST=$(grep $Server foobar | awk '{ print $3 }')
echo "Server = $Server"
echo "FDate = $FDate"
echo "ST = $ST"
done < inputfile
The first ST var gives the output "Usage: grep [Option]... Pattern [File]" for each iteration which means its not reading the command correctly.
The second ST var that is commented out actually breaks the entire script cause all the other variables to be empty when it tries to echo.
Now when I try doing the same thing on the command line it works:
$ testme=$(cat foobar | grep Big | awk '{ print $3}'
$ echo "$testme"
tada
So my question is how do I store that grep command in the variable? The pattern match has only one possible result so I don't have to worry about multiple matches. But each server in the loop might have a different string in column 3 (tada,tada1,tada2)
EDIT:
The inputfile has a list of servers with multiple columns. I'm taking the server listed in column 1 of that current line and searching the foobar file for a match and getting the string from column 3.
I've found that the script actually does work even though it's giving the 'Usage' message. Probably because some of the server entries in the inputfile aren't yet in the foobar file so grep doesn't have a match but still tried to pipe it to awk. I don't know that for certain.
I'd still like to eliminate the 'Usage' messages though. I think maybe a 'set -o pipefail' might work but I'd rather not do that.
set -x
. – G-Man Says 'Reinstate Monica' Sep 01 '21 at 03:15Server
variable is not set, or is set to a value that confuses grep (e.g., a value that contains white space). Therefore, it would be interesting to know the output ofecho "Server = $Server"
. – berndbausch Sep 01 '21 at 03:21$Server
variable is empty, e.g. Also, you don't need tocat
a file ogrep
and pipe the result toawk
-awk
can do all that on its own. If you would provide example input with desired output, someone might come up with a more efficient solution ... – AdminBee Sep 01 '21 at 07:22inputfile
contains some empty lines, so the unquoted$server
expands to nothing – steeldriver Sep 01 '21 at 11:18