LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Running a script on all files in a directory tree (https://www.linuxquestions.org/questions/linux-newbie-8/running-a-script-on-all-files-in-a-directory-tree-688140/)

jdwilder 12-03-2008 06:08 PM

Running a script on all files in a directory tree
 
I am attempting to run a c++ program on all the images in a directory and all of its sub directories. To do this I run

find . -type f -exec file '{}' \;

The c++ program outputs the results to standard out, and I want to redirect to a file for each image, so if the program is running on a.jpeg I want a file called a.txt (or a.jpeg.txt would be fine).

I try

find . -type f -exec file '{}' > '{}'.txt \;

But this only creates a file named {}.txt. How do I get it to recognize the {} as the name of the current file after the >?

Is there a way to do this in one command on the command line (or a different post I failed to find that explains how)?

Tinkster 12-03-2008 07:32 PM

By not wrapping it in single quotes? Just kidding - that's only
half the problem. The other half is that you can't use the {}
twice ...
Use a wrapper:
Code:

for i in $(find -type f)
do
  file ${i} > ${i}.out
done


jdwilder 12-04-2008 10:06 AM

Solved
 
Works, thank you!

i92guboj 12-04-2008 10:20 AM

The problem is solved. However I will make a slight comment for the sake of correctness.


Quote:

Originally Posted by Tinkster (Post 3363643)
By not wrapping it in single quotes? Just kidding - that's only
half the problem. The other half is that you can't use the {}
twice ...

The real problem is not using it twice. You can easily check that using it twice is not a problem if you do this:

Code:

for i in $HOME -mexdepth 1 -exec echo '{}' '{}' \;
It should work as expected, printing the name of every file in the home folder two times in a row.

The problem with his expression is that the redirection operator takes precedence (and anyway, even if it didn't, find doesn't have a meaning for it anyway. So, the find command ends where the redirection starts, and the second '{}' is not in the land of find, but in the land of bash, outside find. For bash, '{}' has no special meaning, and is a textual string (and so, it's printed as that, without any kind of expansion attached to it.

So, piping the names into a loop is probably the best way:

Code:

find whatever | while read file
do
  file "$file" > "${file}.log"
done

Note proper usage of quotation as well. Otherwise you'll have problems with file names containing spaces or any other special character.


All times are GMT -5. The time now is 11:21 PM.