Bash – List files with line count and date

bashlsshelltext processingwc

I want to be able to list files showing the number of lines the each file has and the date. I can happily get the line count using wc -l *. Not a problem. I can get the date using ls -l.

Is there a way to combine the two commands to give me a single output in columns?

Best Answer

Here is something with find + wc + date.

find . -maxdepth 1 -exec sh -c '[ -f "$0" ] && \
  printf "%6s\t\t%s\t%s\n" "$(wc -l<"$0")" "$(date -r "$0")" "$0"' {} \;

Instead of date -r one can also use for example stat -c%y.

The output looks like this:

   394      Thu Oct 16 22:38:14 UTC 2014    ./.zshrc
     7      Thu Oct 30 11:19:01 UTC 2014    ./tmp.txt
     2      Thu Oct 30 06:02:00 UTC 2014    ./tmp2.txt
    40      Thu Oct 30 04:16:30 UTC 2014    ./pp.txt

Using this as starting point one can create a function which accepts directory and pattern as parameters:

myls () { find "$1" -maxdepth 1 -name "$2" -exec sh -c '[ -f "$0" ] && \
  printf "%6s \t\t%s\t%s\n" "$(wc -l<"$0")" "$(date -r "$0")" "$0"' {} \;; }

After that myls /tmp '*.png' will list only images from /tmp (notice single quotes around pattern to prevent shell from expanding a glob operator *).

Related Question