views:

92

answers:

4

I need some assistance in creating a shell script to run a specific command (any) on each file in a folder, as well as recursively dive into sub-directories.

I'm not sure how to start.

a point in the right direction would suffice. Thank you.

+2  A: 

To recursively list all files

find . -name '*'

And lets say for example you want to 'grep' on each file then -

find . -type f -name 'pattern' -print0 | xargs -0 grep 'searchtext'
Gopi
The `-name '*'` is not what you want. It should be `-type f` to match only files. And to execute a command, use `-exec`, not a pipe.
Borealid
grepping `/dev/urandom` might take a while ;-) I suggest adding `-type f`
mvds
Yep. Thanks for the correction.
Gopi
as for grepping you'd better just `grep -R` ;-)
mvds
+4  A: 

You should be looking at the find command.

For example, to change permissions all JPEG files under your /tmp directory:

find /tmp -name '*.jpg' -exec chmod 777 {} ';'

Although, if there are a lot of files, you can combine it with xargs to batch them up, something like:

find /tmp -name '*.jpg' | xargs chmod 777

And, on implementations of find and xargs that support null-separation:

find /tmp -name '*.jpg' -print 0 | xargs -0 chmod 777
paxdiablo
+3  A: 

To apply a command (say, echo) to all files below the current path, use

find . -type f -exec echo "{}" \;

for directories, use -type d

mvds
thanks! that got me what i needed!
Kirby
A: 

Bash 4.0

#!/bin/bash
shopt -s globstar
for file in **/*.txt
do
  echo "do something with $file"
done
ghostdog74