Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print file details of files matching grep pattern

I want to print file details along with grep output but unable to do so. E.g., for the command

grep 3456 A.txt

I get the output

A.txt

but would like the output

-rw-rw-r-- 1 tarun tarun   41356911 Aug 25 01:31 A.txt

I tried the following without success:

  1. grep 34567 A.txt | xargs ls -tlr

  2. grep 34567 A.txt | while read line ; do echo "$line" | date %s.%N ; done

  3. grep -Hr 34567 A.txt | awk -F: '{"stat -c %z "$1 | getline r; print r": "$0 }'

  4. grep 34567 A.txt | awk -F: '{"date -r \""$1"\" +\"%F %R\"" | getline d; print d,$0}'

like image 428
Tarun Avatar asked Aug 25 '16 12:08

Tarun


2 Answers

grep -Zl 3456 * | xargs -0 ls -l

with GNU grep. The options are:

  • grep -Z and xargs -0: separate output names by a NULL byte instead of by whitespace. This way you can handle filenames that include spaces.
  • grep -l: print only the filenames that match
  • ls -l: Standard ls long output, which appears to be what you are asking for.

Tested on latest cygwin.

like image 92
cxw Avatar answered Oct 18 '22 04:10

cxw


There isn't need for xargs here; find can be used to both run grep and run ls, or even to emit ls-style output itself.

find . -maxdepth 1 -type f \
       -exec grep -q -e '1234567' -- '{}' ';' \
       -exec ls -l {} +

...or, even better:

find . -maxdepth 1 -type f \
       -exec grep -q -e '1234567' -- '{}' ';' \
       -ls

The -ls action uses an output format akin to ls -l.

like image 1
Charles Duffy Avatar answered Oct 18 '22 03:10

Charles Duffy