4

I have 10 files. I can list them with find . -type f and what I am trying to achieve is sending a message to all 10 files after finding them with find command.

What I have tried, find . -type f -exec echo "This file found" >> {} \;

May be logically I am right but its not working. Is there any way I can achieve with using find and echo only ?

Thank you

Raja G
  • 5,973
  • 14
  • 49
  • 82

1 Answers1

10

The shell redirection, >> is being done at first, a file named {} is being created before even the find starts and the strings (the number of files are in there) are being written to the file {}.

You need:

find . -type f -exec bash -c 'echo "This file found" >>"$1"' _ {} \;
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • You again , oh man. How do you know these many things. :P dont say learning. – Raja G Aug 09 '16 at 06:22
  • @Raja Perfect timing i guess :P – heemayl Aug 09 '16 at 06:23
  • Yes Heemayl. Thank you again. :) – Raja G Aug 09 '16 at 06:27
  • I don't get the purpose of `_`. Why not using `$0` instead of `$1` without the character `_`? – oliv Aug 09 '16 at 07:01
  • Technically, the first argument to `bash -c "..."` is the value used for `$0`, not the first positional argument. You *could* use `bash -c "echo "This file found" >> "$0"' {}`, but that's arguably abusing the `$0` parameter. (I'm not aware of any problems that could occur if you did, though.) – chepner Aug 09 '16 at 12:30
  • 1
    @chepner I'm not convinced with your explanation... at least this is not what man pages say. I ask a question [here](http://stackoverflow.com/q/38866883/2214695) – oliv Aug 10 '16 at 07:30