Return all files of a specific extension with directory and subdirectories paths

using terminal on MAC OS I need to return path along with the file name in the a directory and all sub-directories, but only if a fie has a specific file extension (e.g. .txt).

I tried this, but it does not filter by file extension:

find $PWD/* -maxdepth 20

I also tried this, but it does not return me a directory path:

ls my-dir  |egrep '.txt$'
Asked By: Data Engineer


Read man find. These are the right ways:

find "$PWD" -type f -name '*.txt' -print

or, if the filenames contains spaces or other "funny" characters (by standard anything except / and NUL 0x00 is allowed):

find "$PWD" -type f -name '*.txt' -print0 | 
    xargs -0 -r stat -c "%Nn"

Read man xargs stat.

Answered By: waltinator

If you’re on macos, then your shell is likely zsh, then:

print -rC1 -- $PWD/**/*.txt(N)

Would print raw on 1 Column the full paths of the non-hidden files (of any type including regular, symlink, fifo…) whose name ends in .txt in the current working directory or below, sorted lexically

Add the D qualifier (inside the (...) above) to include hidden ones, . to restrict to regular files only, om to sort by age, :q to quote special characters in the file paths if any…

For head and tail of those paths in 2 separate columns:

() {print -rC2 -- $@:h $@:t; } $PWD/**/*.txt(N)

Where we pass that list of paths to an anonymous function which prints the heads and tails of its @rguments on 2 Columns.

Answered By: Stéphane Chazelas