automatically prefix files with holding directory name

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

Moderator: Mr_Noodle

I wish to prefix files in a subdirectory with the name of that directory.

I have a working shell script to do this invoked by script.sh <filenames>

#!/bin/bash

for f in "$1" ;
do mv "$f" "${PWD##*/}""_""${f/_*_/_}";
done

or recursively

#!/bin/bash

for i in $(ls); do # runs through the 'items' in this dir
if [ -d $i ]; then # if this is a dir
fname=${i##*/} # pick up the dir name which will be used as prefix
echo $fname
cd $i # move into the dir
for z in *; do # loop over files
# echo $z
mv $z ${fname}_${z} # put the prefix to the file.
done
cd ..
fi
done


But trying to embody in a Hazel rule (go into subfolders, execute script on any file NOT folder doesn't work.

The Hazel embedded script is:

mv "$1" "${PWD##*/}""_""${1/_*_/_}";

I know I am missing something key - grateful for pointers.
rleaver152
 
Posts: 10
Joined: Sun Apr 30, 2017 3:24 pm

Without seeing the rule I can't say for sure but it may be that you are combining folder and file logic into one rule incorrectly. Search the manual as there is a chapter that goes into more detail on that.

That all said, you can do this without a script. Try something like:
Code: Select all
    If (all) are met
        Kind is not folder
        If (all) are met for (the enclosing folder)
            Name matches (•parent folder name)
    Do
        Rename (•parent folder name) (name)

where (•parent folder name) is configured to match "anything". What the above does is grab the parent folder name into a custom attribute which you can then use in the Rename action.
Mr_Noodle
Site Admin
 
Posts: 11195
Joined: Sun Sep 03, 2006 1:30 am
Location: New York City

worked beautifully, thanks
rleaver152
 
Posts: 10
Joined: Sun Apr 30, 2017 3:24 pm


Return to Support