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

使用find命令-exec选项查找目录并创建带内容文件的问题求助

使用find命令-exec选项查找目录并创建带内容文件的问题求助

Hey Jason, let's figure out why your command isn't working and fix it up! There are a couple of small issues with your original line that are throwing things off.

First, let's break down the problems in your command:

  • You wrote -type -d — that's a syntax error! The correct flag for finding directories is -type d (no extra hyphen before the d).
  • When you use > inside the -exec like that, the redirect gets handled by your outer shell instead of being run for each directory found. That means if find locates multiple directories, you'll just keep overwriting the same /myfile.txt over and over (and maybe not even get the newline you want).

Let's cover two common scenarios you might be aiming for:

Scenario 1: Create a myfile.txt with content inside every directory found

This is probably what you want if you need the file in each matching directory. Here's the fixed command:

/bin/bash -c "find directory -type d -exec sh -c 'echo -e \"some content with new line \n\" > \"{}/myfile.txt\"' \;"

Let's break this down:

  • -type d fixes the directory type flag
  • We wrap the echo/redirect in sh -c so the redirect happens per-directory (not just once by the outer shell)
  • echo -e tells echo to parse the \n as an actual newline (without it, you'll just see the literal \n in your file)
  • Wrapping "{}/myfile.txt" in quotes ensures it works even if your directory names have spaces or special characters

If you prefer a more reliable way to handle the newline (using bash's ANSI-C quoting), you can adjust it like this:

/bin/bash -c 'find directory -type d -exec sh -c '\''echo $'\''some content with new line \n'\'' > "$1/myfile.txt"'\'' sh {} \;'

This uses $'...' to make sure the newline is interpreted correctly without relying on echo -e.

Scenario 2: Create one single /myfile.txt if any directory is found

If you just need to create the file once (even if multiple directories are found), fix the syntax and add -quit to stop find after the first match (so you don't overwrite the file repeatedly):

/bin/bash -c "find directory -type d -exec sh -c 'echo -e \"some content with new line \n\" > /myfile.txt' \; -quit"

A quick tip: If your content has special characters (like quotes or backslashes), double-check how you're escaping them — wrapping content in single quotes can help avoid messy escaping, just make sure you handle the nested quotes correctly in the overall command.

备注:内容来源于stack exchange,提问作者jason135

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 07:58:04