How to recursively edit path of symlinks? This is an additional question that began with this one - How to edit Symbolic Links in OS X?

Now that I know how to edit the path symlinks point to, I'm trying to figure out how to do this recursively for any broken symlink.  I'm a PHP guy, so this CLI stuff is somewhat foreign to me...

There seems to be a few specific elements to this, namely:


Identify a broken symlink and retrieve its location
Get the old, now-incorrect, destination for the symlink
Construct the new correct path for the symlink to point to
Edit the symlink


The first is fairly easy:

find /path/to/search -type l | while read f; do if [ ! -e "$f" ]; then ls -l "$f"; fi; done

This gets me a nice list of all broken symlinks found below the supplied directory.  But I believe I would need to store the location of each in a variable (array?) to work with it.  

Next, it seems that changing the action supplied in the "then" portion of the logic, would yield the solution.

Item 2 can be retrieved using:

readlink /path/to/broken/symlink

So it seems we need to shove that into a variable.  I'm unclear on how to do this in terminal.

Number 3 would be a simple edit to the path retrieved during step 2.  I need to replace the old drive name, with the new.  So changing:

/Volumes/Old\ Drive/path/to/symlink

to

/Volumes/New\ Drive/path/to/symlink

Also unclear on exactly how to do this within a CLI script.  Some sort of string replacement appears to be needed.  Something like str_replace in the PHP world.

Finally step 4 can be done via:

ln -f -s /path/to/new/location/of/original /path/to/location/of/broken/symlink/

as detailed in my other question, previously linked above.

How exactly would I string these concepts together, to accomplish my desired outcome of fixing all my symlinks in one shot?
From the top of my head (and without any testing at all):


Create a text file with the following content

#!/bin/bash

find "$1" -type l | while read symlink; do
    if [ ! -e "$symlink" ]; then
        old_path=$(readlink "$symlink")
        new_path=${old_path/Old Drive/New Drive}
        ln -f -s "$new_path" "$symlink"
    fi
done

Make it executable by running chmod +x name-of-file
Run ./name-of-file /path/to/search


This is untested so try it with a sample directory first.



To add some explanations


old_path=$(readlink "$symlink") runs the command in $(...) and assigns the result to $old_path
${old_path/Old Drive/New Drive} does text substitution on $old_path