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

如何在BASH中使用find命令列出不带目录前缀的文件名

方案1:输出 images/文件名 格式路径

直接修改find命令使用-printf参数拼接路径,修改后的完整代码如下:

OIFS="$IFS"
IFS=$'\n'
images=website/images
# %f 表示仅获取文件名,前缀拼接images/即可
dirlist=$(find "$images" -type f -printf "images/%f\n")
echo "$dirlist"
# 用完可以恢复IFS,避免影响后续其他命令
IFS="$OIFS"

如果你的环境不支持find的-printf参数,也可以用sed替换路径前缀:

dirlist=$(find "$images" -type f | sed 's/^website\///')

输出示例:

images/Todiste71.png
images/Torsion.png


方案2:输出无目录前缀的纯文件名

同样修改find命令,直接输出文件名即可:

OIFS="$IFS"
IFS=$'\n'
images=website/images
dirlist=$(find "$images" -type f -printf "%f\n")
echo "$dirlist"
IFS="$OIFS"

不兼容-printf的话可以用basename处理:

dirlist=$(find "$images" -type f -exec basename {} \;)

输出示例:

Todiste71.png
Torsion.png


注意事项

  • 变量调用时建议加双引号包裹(如"$images"),避免路径或文件名包含空格时出现解析错误
  • 你原来设置的IFS=$'\n'可以保留,完美适配文件名包含空格的场景,for循环遍历不会异常拆分

内容的提问来源于stack exchange,提问作者Gary Kong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:00:04