How to grep variable in shell script?

Hi Team,

I am trying to grep date in a file but it is not working

#!/bin/bash
d=`date "+ %Y%m%d %H:%M"`
cd /scripts
/bin/rm -f test1
cat /var/logs/File.txt.0 |grep $"d" >v.txt

instead it is showing the complete file output.
kindly suggest how should i grep this variable

it works fine if I search manually

 
 cat /var/logs/File.txt.0 |grep "20180321 18:54"| head
 [20180321 18:54:03.196000] Module:
1 Aff.Obj: Info: 
[20180321 18:54:17.074395] Module:
j: 10.239.128.10:6789 Info: 
[20180321 18:54:33.197000] Module:

 

scriptor

Try "$d" .

#!/bin/bash
d=`date "+ %Y%m%d %H:%M"`
cd /scripts
/bin/rm -f test1
fgrep "${d}" /var/logs/File.txt.0 >v.txt

You DON'T need to cat a file into grep - grep can pick up a file itself.

You got $d wrong. It should have been "$d" or preferably (as I have put) "${d}". You put $"d".

I used fgrep here instead of grep as that searches for strings, rather than regular expressions.

Andrew

Hi Andrew/Rudic,

I tried both the option suggested by you.
however I am not getting any output.

please suggest.

 
 # set -x
# cat /var/logs/File.txt.0 |grep "${d}" | head 
+ grep ' 20180322 11:56'
+ head
+ cat /var/logs/File.txt.0
 
 
 # set -x
# echo $d
+ echo 20180322 11:56
20180322 11:56
# fgrep "${d}" /var/logs/File.txt.0 | head 
+ head
+ fgrep ' 20180322 11:56' /var/logs/File.txt.0
#
 

You have a leading space in d that doesn't seem to exist in your file.

Hi

I don't see any space in my file.

also I tried again still not working.

#d=`date "+ %Y%m%d %H:%M"`
++ date '+ %Y%m%d %H:%M'
+ d=' 20180322 14:14'
#
#
# cat /var/logs/File.txt.0 |grep "$d"
+ grep ' 20180322 14:14'
+ cat /var/opt/fds/logs/EventLogFile.txt.0

#

The bit in red. Rudi said the space was in d .
Try this instead:

d=`date "+%Y%m%d %H:%M"`

Andrew

1 Like

thx a Andrew now its working