Operating System - HP-UX
1821051 Members
2746 Online
109631 Solutions
New Discussion юеВ

grep and strings with spaces

 
SOLVED
Go to solution
Manuales
Super Advisor

grep and strings with spaces

hi
i have:
a=`date "+%b %d"`
echo $a = "Apr 25"

if i run:
cat log | grep $a
$ cat log | grep $a
grep: can't open 25


how can i fix it ..
7 REPLIES 7
Manuales
Super Advisor

Re: grep and strings with spaces

is correct:

cat log | grep "$a"

├В┬┐?
Steven Schweda
Honored Contributor
Solution

Re: grep and strings with spaces

If it works, it's probably correct.
Kapil Jha
Honored Contributor

Re: grep and strings with spaces

see if u doing grep $a it will be replace by
grep Apr 25
so it would search Apr and not "Apr 25"
that is why this error.
Hope u got it.
BR,
Kapil
I am in this small bowl, I wane see the real world......
CharlesC
Advisor

Re: grep and strings with spaces

This is how I make it work:

month=`date +%b`
day=`date +%d`
echo $month' '$day
grep "$month' '$day" syslog.log


What if...
CharlesC
Advisor

Re: grep and strings with spaces

Seems this website cannot show more than one space too. This is a re-post:

month=`date +%b`
day=`date +%d`
echo $month'BB'$day
grep "$month'BB'$day" syslog.log


Note: BB means 2 x space.
What if...
James R. Ferguson
Acclaimed Contributor

Re: grep and strings with spaces

Hi Manuales:

You need to quote the variable:

# grep "$a" log

...so that the shell doesn't expand the variable into "

# grep Apr 25 log

...before 'grep' sees it.

That said, do NOT spawn an extra process (the 'cat') merely to read the file and pipe it to 'grep' which is only going to read (again!) the output of the pipe. Many standard Unix utilities are written to consider the final arguments as files to be read. In fact, the error 'grep: can't open 25' in the case above, is 'grep' telling you that it can't find what it thinks is a file named "25".

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: grep and strings with spaces

>CharlesC: cannot show more than one space too

There is a box "Retain format" you can check keep the spaces, " ".