使用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 thed). - When you use
>inside the-execlike that, the redirect gets handled by your outer shell instead of being run for each directory found. That means iffindlocates multiple directories, you'll just keep overwriting the same/myfile.txtover 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 dfixes the directory type flag- We wrap the echo/redirect in
sh -cso the redirect happens per-directory (not just once by the outer shell) echo -etells echo to parse the\nas an actual newline (without it, you'll just see the literal\nin 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

