Sunday, February 20, 2011

Automator - Get folder name using Shell Script


I wanted to move a folder from Movies to Music and rename both the folder and the videos.

Challenge was to 
1) Pass output of previous action to shell script.
2) Get the folder name.

#1 Passing output of previous action to shell script
Once you drag and drop Utilities/Run Shell Script action and change drop down "Pass Input" to "as arguments", it becomes evident that the values are passed in the usual way command line variables are passed to a shell script in Unix. i.e. in $@

If you see in the automator workflow above, I'm getting all the file names in the folder as $@ in my script. You might know that we can access the contents of $@ as $1, $2 etc and $# gives the total number of variables, in this case number of files.

Here's how I went over the list of files and renamed them all.

#Say for example $@ has "/Users/ruchi/Movies/Snowboarding 2010/videofile1.AVI /Users/ruchi/Movies/Snowboarding 2010/videofile2.AVI"
while [ ! -z "$1" ]
do
mv "$1" "`echo "$1" | sed 's/\[[aA-zZ,.]*\] [aA-zZ, ]* - [0-9][0-9] - //g'`"
shift
done

#2 Getting the folder name
This is more of a hack. I already had file names with path in #1, I checked the depth of my the folder from home (/Users/ruchi/) and used awk to get the folder name from a file name.

#for example let's say $1 has /Users/ruchi/Movies/Snowboarding 2010/videofile1.AVI
foldername=`echo "$1" | awk -F/ '{print $5}'` # That's right, not $4 but $5 due to leading "/"
echo $foldername #output: Snowboarding 2010

Here's another tutorial on how to pass variables to shell script.

1 comment:

  1. Hi! I'm not sure I understand everything you did (because I know nothing of shell script) but this post is interesting. I love automator, and get folder name is one tricky thing to do. I have my method to do so without using script, but my method is limited because I have to use one single directory written in the .app

    What I do is
    (drag folder in the .app)
    - set value of variable (which outputs something like /users/home/folder1/folder2/)
    - [process I have to do]
    - Name the output with something I'll change later for example XX
    - Rename to replace XX with the variable made before (/users/home/folder1/folder2/)
    - Rename again to cut what is useless in the path here /users/home/folder1/
    - So that the Output file is named folder2.
    I've made a video that shows it http://youtu.be/M1jOeoio5fA


    For me it's not a problem since I always have /users/home/desktop/ to replace but it can't work somewhere else without rewriting the app.

    ReplyDelete