Running shell script on the contents of a folder

Get help. Get answers. Let others lend you a hand.

Moderator: Mr_Noodle

I am trying to automate the collection of individual .txt files into a single, larger file. To do this, I wrote a shell script that works when I run it in terminal:
Code: Select all
for f in *.txt ; do
    cat "$f" >> COMPILED
    echo "***###***" >> COMPILED
done
rm *.txt


I have a number of subfolders I'd like this to apply to and keep those compiled documents in their original subfolders. I have a go into subfolders rule in place on the parent folder. I then made a simple rule that matches any file with the .txt extension

Code: Select all
If all of the following conditions are met:
      Extension is .txt
Do the following to the matched file or folder:
     Run shell script embedded script


Obviously, I don't want the rule to run on the .txt file, but run in any directory that contains .txt files.

When I run this, I get a COMPILED document in the parent folder that is empty even though there are text files in the subfolders. I did some reading and found that I need to tell the shell script to CD to the folder of interest. When I followed up on this, I found some issues with the $0 and $1 variables. Instead of giving a file name, I get the entire contents of the text document. For example, $0 gives all of the code for the shell script and $1 gives the one line of text I put in the test.txt. When I use $0 or $1 in the terminal, I get the expected script name/first argument.

I think I need a way to get the path for the directory containing the text files to be compiled, but all the examples I've seen for this are based on using $1. Is this an issue with my shell script or the way I'm setting up the hazel rules?

Thanks for your help
Cloverleaf
 
Posts: 2
Joined: Mon Jan 20, 2014 4:28 pm

Have your rule match the folder and not the files. If you want to match folders with text files then do the following:

- Hold down option while clicking the + button to create a new condition. This will create a nested condition.
- Set the target of the nested condition to either "any sub-file" or "all sub-files" depending on your needs.
- Add the condition to match text files under that.

That will match folders that contain txt files which seems like what you want here.
Mr_Noodle
Site Admin
 
Posts: 11255
Joined: Sun Sep 03, 2006 1:30 am
Location: New York City

Thanks so much, this worked.

Any of its subfiles or subfolders:
Extension is .txt

Code: Select all
cd "$1"

for f in *.txt ; do
    cat "$f" >> COMPILED
    echo "***###***" >> COMPILED
done
rm *.txt


Runs this script in any folder with text files like I want it to.
Cloverleaf
 
Posts: 2
Joined: Mon Jan 20, 2014 4:28 pm


Return to Support