Help with grep to show date/time of file

Hi,

This is similar to what's been asked in the post below:

The solution sort of work / not work, the problem is if there is no match, then xargs does a full listing. That is if it found file/s that matches the search string and hence file exist, it does list the files but if it doesn't find a match it do a full listing instead :frowning:

See example below:

$: ls -ltr
total 16
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file1
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file2
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file3
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file4
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file5
-rw-r-----   1 tester   omg            15 Mar 19 09:36 corrupt.txt
$: grep -il "bad" * | xargs ls -l
-rw-r-----   1 tester   dba           15 Mar 19 09:36 corrupt.txt
$: grep -il "corrupt" * | xargs ls -l
total 16
-rw-r-----   1 tester   omg            15 Mar 19 09:36 corrupt.txt
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file1
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file2
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file3
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file4
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file5
$: uname -a
SunOS [hostname] 5.11 11.3 sun4v sparc sun4v
$: cat corrupt.txt
BAD FILE FOUND

And just realized I can just actually just do ls -l but it gave me the same behaviour:

$: ls -l `grep -il "bad" *`
-rw-r-----   1 tester   omg            15 Mar 19 09:36 corrupt.txt
$: ls -l `grep -il "corrupt" *`
total 16
-rw-r-----   1 tester   omg            15 Mar 19 09:36 corrupt.txt
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file1
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file2
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file3
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file4
-rw-r-----   1 tester   omg            0 Mar 19 09:36 file5

I guess this is the expected behavior but kinda hoping it'll just do nothing if it doesn't find any or print something maybe instead? Any suggestion?

No surprise. If the grep "command substitution" delivers the "empty" value, ls-l uses the default: . . man ls :

Add a certainly non-existent file name (difficult to find, as there are almost no restrictions on file names), and suppress stderr output:

ls -l $(grep -il "corrupt" *) FALSE 2>/dev/null

EDIT: or, check the grep result upfront, and just don't call ls if empty...

1 Like

Thanks for the explanation