For generic advice regarding processing of file names potentially containing spaces, see Why does my shell script choke on whitespace or other special characters?
The difficulty with what you're trying to do is that there's no nice way to list the N most recent files with standard tools.
The easiest way to do what you're doing here is to use zsh as your shell. It has glob qualifiers to sort files by date. To run file
on the 500 most recent files:
file *(om[1,500])
With the Linux file
utility, pass the -i
or --mime-type
option to get output that's easier to parse. Image files are identified by lines ending with image/something
.
file --mime-type *(om[1,500]) | sed -n 's~: *image/[^ ]*$~~p'
If you need to cope with absolutely all file names, including those with a newline in their name, use the -0
option for null-delimited output. Recent versions of GNU sed can use null bytes as the record delimiter instead of newlines.
file --mime-type -- *(om[1,500]) | sed -zn 's~: *image/[^ ]*$~~p'
If you don't have zsh, you can use ls
and cope with file names that contain spaces but not newlines or trailing spaces by passing the -L1
option to file
. This invoked file
on one file at a time, so it's slightly slower.
ls -t | head -n 500 | xargs -L1 file --mime-type -- | sed -n 's~: *image/[^ ]*$~~p'
xargs
implementations, the delimiter can be changed, for example to'\n'
. This is often helpful when the input is not generated byfind
. See-d
(GNU) and-E
(OSX) – MattBianco Feb 27 '17 at 09:39xargs -d '\n\
doesn't appear to recognize newlines properly. – Michael Apr 20 '23 at 22:50