Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I store downloaded files in a log like this:

[source] filename

To avoid downloading a file more than once I grep for [source] filename before:

if ! grep "$signature" downloaded.log > /dev/null; then
    wget ...
fi

but starting my line with [ grep does not work the way I need:

signature="[source] filename"
echo $signature | grep "$signature"
echo $signature | grep "\$signature" #trying to escape first bracket

both return nothing.

Any smart workaround?

It would be nice also having no need to change the code switching to parens (), braces {}, or whatever <>

share

1 Answer 1

up vote 5 down vote accepted

First you have to quote your variable, then you should use -F --fixed-strings switch to avoid interpreting the brackets as regular expression meta characters:

echo "$signature" | grep -F "$signature"

Then you should also use -q --quiet switch too, so grep exit as soon as found the first occurrence. This only for speed consideration:

if ! grep -Fq "$signature" downloaded.log; then
    wget ...
fi
share
    
Thank you, I'm going to test it. You are right about quoting variables, just forgot them writing question –  neurino Oct 21 '11 at 15:15
    
@neurino One more thing: you should add the -x (match whole line) option to grep, otherwise a line like [foo] I say [source] filename, so there! will match. Note that this means [source] filename2 won't match (definitely desirable), nor will [source] filename was read (may or may not be desirable). –  Gilles Oct 21 '11 at 16:41
    
@Gilles: -x option is definitely desirable, thank you very much –  neurino Oct 21 '11 at 18:15

This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .