0

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$'
1
  • 1
    You mention MAC OS in the body of your question but Linux in tags. Are you running a Linux-based OS on some Apple Macintosh hardware or are you running macos (and therefore not Linux)? Commented Nov 5, 2023 at 18:03

2 Answers 2

1

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.

3
  • Thanks a lot @Stéphane Chazelas. Any idean ho to do the same, but print out 2 columns, one just path, and 2nd one just file name with its extension? (e.g. column a: /Users/John/Documents ; columnm b: my_flat_file.txt) Commented Nov 6, 2023 at 14:51
  • 1
    @DataEngineer, see edit. Commented Nov 6, 2023 at 16:10
  • Works perfectly fine @Stéphane Chazelas. I'm very gratitude your help! Commented Nov 6, 2023 at 17:14
0

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 "%N\n"

Read man xargs stat.

3
  • Why use PWD instead of .? For the full path? And why the print? Much more, why bother parsing it? There is no need for null separated output if you don't require parsing the list of file names. Stat is just giving you the name you already have.
    – terdon
    Commented Nov 5, 2023 at 18:09
  • @terdon, with -c %N (which implies GNU stat; while the OP likely has FreeBSD stat instead), you get the Quoted file name with dereference if symbolic link, so something like '/path/to/link.txt' -> 'target'. Commented Nov 5, 2023 at 18:13
  • I don't understand the stat command. First of all, why \n at the end? It already adds newline by default. Second, if it's GNU stat, than why use %N? Is it just to get the name quoted? Why not use -printf "'%p'\n" on the find command instead?
    – aviro
    Commented Nov 6, 2023 at 14:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .