I'd like to grep the output of ls and pipe it into less so I can scroll through the output.

This doesn't work, but ideally, I'd be able to type this:

ls -alh | grep "file" | less

Any suggestion how to do this? My over-all goal is to view the modification dates of all files in the current directory which contain "file" in their filenames. I have read into stat but this seems too verbose for my purposes.

  • 2
    Why doesn't this work? That will correctly pipe the output of ls -alh | grep "file" to less. Are you expecting less to open file? – terdon May 25 '19 at 21:04
  • It may be a speed issue actually. I didn't create a minimal test case so am running this on a folder with 20k files in it (and through ssh if that makes a difference). I didn't let it work for more than a few minutes... – kevinkayaks May 25 '19 at 21:05
  • 2
    Minutes? That's surprising. But at least try ls -alh *file* | less first, there's no need for grep here. – terdon May 25 '19 at 21:07
  • 4
    @terdon That should probably be ls -alhd -- *file* to avoid listing the contents of directories and to protect from files whose name start with a dash. – Kusalananda May 25 '19 at 21:09
  • 1
    Thank Stéphane, it was he who reminded me about the -- (as usual) :-) – Kusalananda May 25 '19 at 21:10

I'm assuming stat being "too verbose" means the command outputs a lot of other information too, which it does by default if you don't request specific bits of info from it.

With GNU stat:

stat --printf '%y\t%n\n' -- *file*

That would output only the modification timestamp in human-readable format followed by a tab and the filename. This will be done on all filenames that contains the substring file. Set the dotglob shell option in bash, with shopt -s dotglob, to also allow hidden filenames to be included.

Use %Y in place of %y to get the modification timestamps in seconds since Epoch instead.

On BSD systems, use

stat -f '%Sm%t%N' -- *file*

instead (does the same thing). Change %Sm to %Fm to get seconds since the Epoch.

See the manual for stat (man 1 stat) on you system for further information.

  • thanks @Kusalanda, this works great. I modified with %w for creation timestamp – kevinkayaks May 25 '19 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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