Search code examples
bashshellloopsgrepxargs

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}'


Solution

  • 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.