I need to edit some Softlinks which are broken because they are absolute. I want to get them to some relative ones. For that I need to count the beginning directory depth of the path they are pointing at. Then I need to replace these counted directories by ../ because I just need to get up, until I find the matching directory.
I have already a line to find the broken links:
find -type l | while read f; do if [ ! -e "$f" ]; then ls -l "$f"; fi; done
This works and so I can find the broken ones, but I have no idea how to continue.
Edit: I found the following solution which works:
depthRoot=2 # Depth of root-directory
find -type l |
while read f
do
if [ ! -e "$f" ] # broken link found (put in variable f)
then
echo "Link found: $f" # output of broken link
previous="$(readlink "$f")" # target of broken link in variable previous
echo "points to: $previous" # output of target
y=$"${f//[^\/]}" # generating string of f with all the slashs
depthFrom=${#y} # count length of y an put value in depthFrom
depthFrom=`expr $depthFrom - 1`
echo "Depth place = $depthFrom" # output of depth of place of broken link
y=$"${previous//[^\/]}" # generating string of previous with all the slashs
depthTarget=${#y} # count length of y an put value in depthTarget
depthTarget=`expr $depthTarget - $depthRoot - 1` # subtraction of depth of root-directory
echo "Depth target = $depthTarget" # output of depth of target of link
depthRoot=`expr $depthRoot + 1` # root-directory-depth +1 (1 Directory - 2 Slashs)
depth=`expr $depthFrom - $depthTarget` # calculate difference in depth
echo "difference of depth = $depth" # output of differrence of depth
while [ $depthRoot -gt 0 ] # while depthRoot > 0
do
depthRoot=`expr $depthRoot - 1` # decrement depthRoot by 1
previous=${previous#*/} # erease everything of previous until first Slash leftside
done
f=${f:2} # subtract ./ of f
tofind="$(echo "$previous"| sed -e 's/[\/&]/\\&/g')" # escape subdirectories of previous
tofind=${tofind%\\*} # erease everything on the right side until first backslash
newlink="$(echo "$f"| sed "s/$tofind//g")" # erease existing side on the left
newlink=${newlink:1}
while [ $depth -gt 0 ] # while depth > 1
do
newlinkaddition=$newlinkaddition"../" # generating ../ for relative links
newlink=${newlink#*/} # remove old directories which will be replaced by ../
depth=`expr $depth - 1` # decrement depth
done
newlink=$newlinkaddition$newlink # generating target of new link
rm $f # erease old link
ln -s "$newlink" "$" # generating new link
echo "new link generated: $newlink -> $f" # output of successfull generation of new link
fi
done