LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   grep works as commandine but fails as varible (http://www.linuxquestions.org/questions/linux-general-1/grep-works-as-commandine-but-fails-as-varible-4175426578/)

jwilleke 09-10-2012 01:58 PM

grep works as commandine but fails as varible
 
grep '^Sep 7' /var/log/warn
Works at command line but:

teststr='^Sep 7'
grep ${teststr} /var/log/warn

Fails as it returns all lines which start with Sep.

Any ideas?

Thanks
-jim

colucix 09-10-2012 02:03 PM

You have to put double quotes around the variable reference to protect the blank space(s):
Code:

grep "${teststr}" /var/log/warn
otherwise the command results in
Code:

grep ^Sep 7 /var/log/warn
which makes grep to look for the pattern "^Sep" in a file named "7" and in the "/var/log/warn" file.

jwilleke 09-10-2012 02:26 PM

That works until it is put in a bash script.
Then it fails to find any entries in the file.

Any ideas?

Thanks

colucix 09-10-2012 02:49 PM

Quote:

Originally Posted by jwilleke (Post 4777109)
Any ideas?

Nope, until you show the current version of your script. Please use CODE tags to embed the lines of code, so that the correct spacing is preserved. I suspect you missed an additional blank space in the pattern, but I can only guess.

In the meanwhile you can compare your code with a working example tested with grep-2.5.4 and bash-4.1.7:
Code:

#!/bin/bash
#
teststr='^Sep  7'
grep "${teststr}" /var/log/warn


YankeePride13 09-10-2012 02:54 PM

Try adding the full path to the grep command in the script as well.

jwilleke 09-12-2012 10:45 AM

Thanks.
With your help and fixing some typos and other errors, we did get this to work.

Code:

#!/bin/bash
REPORTDATE='2012-09-07'
YEAR_MONTH=${REPORTDATE%-*}
YEAR=${YEAR_MONTH%-*}
# Month must be like: Sep 9 from
MONTHSTR=${YEAR_MONTH#*-}
echo $MONTHSTR
DAYSTR=${REPORTDATE##*-}
# Set MONTHSTR to three letter month
MONTHSTR=`date -d 2012/${MONTHSTR}/01 +%b`
# in the war file, there are two spaces for the month number if 0X
# and only one if 1X
if [[ $DAYSTR == 0* ]]
then
  SPACE='  '
  echo 'Set two spaces'
  # Strip any leading 0 from DAYSTR
  DAYSTR="$(echo $DAYSTR | sed 's/0*//')"
else
  SPACE=' '
  echo 'Set one space'
fi
teststr="^${MONTHSTR}${SPACE}${DAYSTR}"
/usr/bin/grep "${teststr}" /var/log/warn

Thanks!
-jim

YankeePride13 09-12-2012 10:54 AM

No Problem, Jim. Please mark the thread as solved and feel free to give reputation points to those who you found helpful!


All times are GMT -5. The time now is 10:39 PM.