Linux – Given two patterns, search specific directories and print last three file names that match each pattern

filesfindlinuxwildcards

How can I shorten this command? The goal is to display the latest 3 files that are in the ABC folder and match uvw in the file name, then do the same but match xyz in the file name.

I'm looking to shorten this since there's a need to add more strings to look for in the future.

find . -name 'ABC' | xargs ls | grep -i uvw |sort| tail -n 3; find . -name 'ABC' | xargs ls | grep -i xyz |sort| tail -n 3

Example output:

2018-06-23T01-23-56.919Z-UVW.gz
2018-06-23T01-29-56.556Z-UVW.gz
2018-06-23T23-26-14.463Z-UVW.gz
2018-08-08T00-16-22.923Z-xyz.js
2018-08-08T00-16-24.517Z-xyz.js
2018-08-08T00-16-25.427Z-xyz.js

Best Answer

With zsh:

set -o extendedglob # best in ~/.zshrc
for w (uvw xyz) printf '%s\n' **/ABC/(#i)*$w*(D[-3,-1]:t)
  • **/: any level of subdirectories
  • (#i): case insensitive matching for what follows
  • (D[-3,-1]:t): glob qualifier
  • D: include hidden files and look inside hidden dirs like find does
  • [-3,-1]: select only the last 3 (globs are sorted in lexical order by default)
  • :t: modifier that extracts the tail of the file path (basename) like your ls does.

Note that if there are several ABC directories, the name of those directories will influence the sorting (files in a/ABC will appear before those in b/ABC).

Related Question