Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use find to append a string to every file in a directory

Tags:

find

bash

exec

I'm trying to append a fixed string to each file in a folder (and its subfolders) whilst skipping the .git directory.

I expected that something like this would work

 find . -type f ! -path "./.git/*" -exec "echo \"hello world\" >> {}" \;

and if I run it with an additional echo it does generate commands that look right

bash> find . -type f ! -path "./.git/*" -exec echo "echo \"hello world\" >> {}" \;
echo "hello world" >> ./foo.txt
echo "hello world" >> ./bar.txt
...

and those commands do what I want when I run them directly from the shell but when I run it from find I get this:

bash> find . -type f ! -path "./.git/*" -exec "echo \"hello world\" >> {}" \;
find: echo "hello world" >> ./foo.txt: No such file or directory
find: echo "hello world" >> ./bar.txt: No such file or directory
...

but those files do exist because when I list the directory I get this:

bash> ls
bar.txt  baz.txt  foo.txt  subfolder/

I guess that I'm not quoting something I need to but I've tried everything I can think of (double and single quote, escaping and not escaping the inner quotes etc...).

Can someone explain what is wrong with my command and how to achieve the the addition of the fixed string to the files?

like image 706
Carcophan Avatar asked Oct 18 '13 10:10

Carcophan


People also ask

How do I find all files containing specific text?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.

How do I search for a string in multiple files?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.


1 Answers

You need to instruct the shell to do it:

find . -type f ! -path "./.git/*" -exec sh -c "echo hello world >> {}" \;
like image 192
devnull Avatar answered Oct 24 '22 18:10

devnull