You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取文件中的glob规则并使用find查找当前目录匹配文件

问题原因

find: paths must precede expression: *.pdf' 该报错是因为原命令的参数传递逻辑不符合find的语法要求: find的-name参数仅接收紧随其后的1个匹配规则,你用xargs直接把所有规则拼接传递后,实际执行的命令等价于: find . -name *.tex .pdf C.png 此时第二个规则.pdf`被find误判为搜索路径,因此触发报错。

正确实现方案

方案1:单条find命令(性能最优,优先推荐)

通过shell数组动态构造find的匹配参数,避免多次调用find,同时兼容含特殊字符的规则:

# 初始化匹配参数数组
match_args=()
# 逐行读取规则写入数组
while IFS= read -r pattern; do
  # 跳过空行
  [ -z "$pattern" ] && continue
  match_args+=(-o -name "$pattern")
done < file.txt
# 执行查找,去掉数组开头多余的-o参数
find . "${match_args[@]:1}"

方案2:简洁一行命令(适合规则量小的场景)

用xargs的占位符参数,每行规则单独调用一次find:

# 过滤空行后逐行传递给find
grep -v '^$' file.txt | xargs -I{} find . -name {}

可选轻量工具方案(可安装fd-find使用)

Ubuntu源里的fd工具对glob匹配支持更友好,写法更简洁:

# 先执行安装:sudo apt install fd-find
xargs -a file.txt -I{} fdfind --glob {}

内容的提问来源于stack exchange,提问作者Arzaan Ul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 19:57:02