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

如何遍历目录运行程序,将输出重定向至输入文件而非STDOUT(fish)

递归处理文件并覆盖原文件方案

Fish Shell 方案

用fish原生循环结合find递归遍历文件,通过临时文件中转避免直接覆盖导致的数据丢失:

# 遍历当前目录下所有文件(递归)
for file in (find . -type f)
  # 运行你的程序,输出到临时文件
  if your-program "$file" > "$file.tmp"
    # 处理成功则替换原文件
    mv "$file.tmp" "$file"
  else
    # 处理失败则删除临时文件并提示
    rm -f "$file.tmp"
    echo "处理文件 $file 失败,临时文件已清理" >&2
  end
end

如果需要只处理指定后缀的文件(比如示例中的txt、cpp、java),可以修改find命令过滤目标文件:

for file in (find . -type f \( -name "*.txt" -o -name "*.cpp" -o -name "*.java" \))
  # 同上处理逻辑
end

Bash/POSIX 兼容方案

用find配合sh批量处理,同样依赖临时文件中转保证安全:

find . -type f -exec sh -c '
  for file do
    if your-program "$file" > "$file.tmp"; then
      mv "$file.tmp" "$file"
    else
      rm -f "$file.tmp"
      echo "处理文件 $file 失败,临时文件已清理" >&2
    fi
  done
' sh {} +

过滤指定后缀的写法:

find . -type f \( -name "*.txt" -o -name "*.cpp" -o -name "*.java" \) -exec sh -c '
  # 同上处理逻辑
' sh {} +

重要提示

绝对不能直接使用 your-program "$file" > "$file" —— Shell会先截断目标文件(清空内容)再启动程序读取该文件,导致程序读取到空内容,最终原文件被损坏。必须通过临时文件中转,确保处理成功后再覆盖原文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:55:25