Home > OS >  bash: Find a directory and create file with content using -exec
bash: Find a directory and create file with content using -exec

Time:12-21

I want to find a directory and create a file with content in the following format, but it's not doing what I want. Any bash expert can help?

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

CodePudding user response:

You need -exec to execute a shell in order to process the redirection.

find directory -type -d -exec sh -c 'printf "content\n" > "$1"/myfile.txt' _ {} \;

{} should be passed as an argument to that shell, rather than being embedded in the shell command, to ensure the shell sees its value properly quoted.

You can make this more efficient by allowing the shell to process multiple files using the -exec ... form.

find directory -type -d -exec sh -c 'for d; do printf "content\n" > "d1"/myfile.txt; done' _ {}  
  •  Tags:  
  • bash
  • Related