简体   繁体   中英

How to match files with `find` in bash - also in subdirectories?

In linux bash, I have directories like this:

.
├── index.md
├── rss.conf
└── tech
    └── comp.md

Where I'm trying to have a list of relative filenames to all *.md files. Looking up some answers here, I've collected: find -name *.md

Which only outputs ./index.md

(Weirdly, If I run the command after a cd ../ it does find all *.md .)

How may I fix this?

Quotes!

find . -name '*.md'

Otherwise, if any file with a name ending in .md exists in the current directory, the glob is expanded by your shell (replaced with a list of matching filenames in the current directory) before find is started.

Note that the . argument (indicating the locations to start from) can be omitted only in GNU find ; including it explicitly is the more portable practice.

find . -name *.md

only finds index.md because the command actually expands to

find . -name index.md

That is, find only sees the one name. (That is how globs work – they expand in the shell before the command is ever executed.)

What you need to do is simply wrap the command in quotes, so the glob doesn't expand.

find . -name '*.md'

In general, if you want to understand why a command is not doing as you expect, run set -x in the shell. That will cause it to output the real command before invoking it.

$ set -x
+ set -x
$ find . -name *.md
+ find . -name index.md
./index.md
$ find . -name '*.md'
+ find . -name '*.md'
./index.md
./tech/comp.md

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM