在 find 中使用 -exec 打印文件扩展名

How*_*ard 4 shell find parameter filenames variable-substitution

我正在玩-execfind 命令的标志。我正在尝试使用该标志来打印文件的扩展名,使用相当新的 Linux 发行版。

从简单开始,这有效:

find . -type f -exec echo {} \;
Run Code Online (Sandbox Code Playgroud)

尝试使用方便的 Bash 字符串功能失败:

find . -type f -exec echo "${{}##*.}" \; (bad substitution)
Run Code Online (Sandbox Code Playgroud)

那么正确的做法应该是什么呢?

jim*_*mij 7

如果您想使用 shell 参数扩展,请使用以下命令运行一些 shell exec

find . -type f -exec sh -c 'echo "${0##*.}"' {} \;
Run Code Online (Sandbox Code Playgroud)


Cap*_*ton 5

 find . -type f | while read file; do echo "${file##*.}"; done
Run Code Online (Sandbox Code Playgroud)

具有绕过所有没人能记住的棘手的 exec 语法的优点。

还有一个优点是只创建一个子进程,而不是为每个找到的文件创建和销毁一个子进程。这比 jimmij 使用 exec 的版本要快得多

# Preparation - 1000 files
for i in {1..1000}; do touch $i.$i; done

>time find . -type f -exec sh -c 'echo "${0##*.}"' {} \;
real    0m21.906s
user    0m6.013s
sys     0m12.304s


>time find . -type f | while read file; do echo "${file##*.}"; done
real    0m0.219s
user    0m0.125s
sys     0m0.087s
Run Code Online (Sandbox Code Playgroud)