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$'
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
.
If you’re on macos, then your shell is likely zsh, then:
print -rC1 -- $PWD/**/*.txt(N)
Would print
r
aw on 1
C
olumn 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 h
ead and t
ail 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 h
eads and t
ails of its @rguments on 2
C
olumns.