LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   using recursion in bash script (https://www.linuxquestions.org/questions/linux-software-2/using-recursion-in-bash-script-462396/)

drkstr 07-09-2006 03:57 PM

using recursion in bash script
 
I need to write a script that preforms an operation on all files in a directory and it's sub-directories. How does one go about doing this in bash? Also, what's the best way to distinguish between a file and a folder?

thanks!
...aaron

spooon 07-09-2006 04:11 PM

use find:

to run "dosomething file" on all the files:
Code:

find . -type f -exec dosomething ’{}’ \;
the "-type f" chooses only files

spirit receiver 07-09-2006 04:19 PM

This is how it works:
Code:

#! /bin/bash
for NAME in $(find /some/directory)
do
  if [[ -d $NAME ]]
  then
    echo "$NAME is a directory."
  fi
  if [[ -f $NAME ]]
  then
    echo "$NAME is a regular file."
  fi
done

If there are many files, it's probably better to use the following loop:
Code:

find /some/directory | while read NAME
do
  ...
done


drkstr 07-09-2006 05:09 PM

Thanks! a mixture of both worked perfectly for me:
Code:

...
find $DIR -type f | while read file
do
  cat $file | sed -e 's/'$IN_TXT'/'$OUT_TXT'/g' > $file
done
...

One other thing though, and sorry this is a bot off topic. There seems to be a limit on how much I can 'cat' ( 68 Kb ). Any way around this?

thanks!
...aaron

**edit**
I'm going to start a new topic since so the information will be easier to find if other people have the same question.

spooon 07-09-2006 08:48 PM

Quote:

Originally Posted by drkstr
Code:

...
find $DIR -type f | while read file
do
  cat $file | sed -e 's/'$IN_TXT'/'$OUT_TXT'/g' > $file
done
...


why not just something like
Code:

find $DIR -type f -exec sed -i 's/'$IN_TXT'/'$OUT_TXT'/g' '{}' \;
note that doing sed on a file and then redirecting it back to the same file doesn't really work, since ">" truncates the file, so you should use "sed -i" to operate on the file in-place


All times are GMT -5. The time now is 10:38 PM.