How to glob all files with an extension in a directory and its subdirectories?

64 Views Asked by At

This feels like it must have an obvious answer, but I haven't yet found one.

Consider this file structure:

A.tsx
B.tsx
dist/C.tsx
dist/D.tsx
src/E.tsx
src/F.tsx
src/G.js
src/component/H.tsx
src/component/I.tsx
src/component/J.js

I want to list all .tsx files in the directory src and all of its descendants.

This lists all .tsx files in src but not its descendants:

ls src/*.tsx

This lists all .tsx files in src's descendants, but not src itself:

ls src/**/*.tsx

Is there a way to glob all .tsx files in src and its descendants in one pattern?

2

There are 2 best solutions below

0
chepner On BEST ANSWER

You need to ensure the globstar option is enabled, or else ** is just interpreted as two adjacent * patterns, each of which will match 0 or more characters, so it's equivalent to src/*/*.tex, which must match some directory under src.

shopt -s globstar
ls src/**/*.tex

should work.

Note that you need bash 4 or later to use globstar. If you are using the system-provided bash on macOS (which is version 3.2), you'll need to install a recent version of bash yourself. (Or switch to zsh.)

1
Sreehari Rajeev On

Try this: ls src/**/*.tsx src/*.tsx