0

when I use this to look to see if there is a particular file in a directory, ls piped to grep does not work

 casper@fooserver:/home/log$ ls -ltr | grep  *FOO-VOL2*

But when I use ls with the file globbing I get results:

casper@fooserver:/home/log$ ls -ltr  *FOO-VOL2*
-rw-rw-rw- 1 casper casper   11489 Sep 24 18:00 FOO-VOL2.20140924.log.gz
-rw-rw-rw- 1 casper casper   11885 Sep 25 18:00 FOO-VOL2.20140925.log.gz
-rw-rw-rw- 1 casper casper       0 Sep 26 08:00 FOO-VOL2.sessiondump.log
-rw-rw-rw- 1 casper casper   60906 Sep 26 18:00 FOO-VOL2.20140926.log
-rw-rw-rw- 1 casper casper   58503 Sep 29 09:00 FOO-VOL2.20140929.log
-rw-rw-rw- 1 casper casper 8259128 Sep 29 09:00 FOO-VOL2.sys.log

What is the difference - the grep to pipe should work.

1
  • The are very different in the corner case where a filename matching *FOO-VOL2* contains a newline; the output of ls will span multiple lines, and grep (assuming a correct regex) will only show the line that contains FOO-VOL2.
    – chepner
    Commented Oct 2, 2014 at 18:01

1 Answer 1

5

The shell expands the *FOO-VOL2* glob before executing anything, so the actual command you're running is this:

ls -ltr |
  grep FOO-VOL2.20140924.log.gz FOO-VOL2.20140925.log.gz FOO-VOL2.sessiondump.log \
       FOO-VOL2.20140926.log FOO-VOL2.20140929.log FOO-VOL2.sys.log

When run with those arguments, grep ignores the standard input coming to it from ls and searches inside the files FOO-VOL2.20140925.log.gz, FOO-VOL2.sessiondump.log, FOO-VOL2.20140926.log, FOO-VOL2.20140929.log, and FOO-VOL2.sys.log for the string "FOO-VOL2.20140924.log.gz". And doesn't find it, which is probably not a surprise.

Also, grep regular expressions and shell glob patterns are different. The patterns you pass to grep are not anchored, so you don't need the equivalent of * on either side of the string you're looking for. But if you did, * doesn't mean "any character" anyway; it means "0 or more of the previous character". So as a grep expression, *FOO-VOL2* is not even valid. You want just FOO-VOL2 or, as a literal translation from the glob even though it includes parts that aren't necessary here, '.*FOO-VOL2.*'.

Not the answer you're looking for? Browse other questions tagged or ask your own question.