Technical stuff, mostly to remind myself when I forget in a couple of months' time.

Wednesday, 6 March 2013

"Editing" symlinks on Linux

Firstly, let's be clear. There *is* no way of editing symlinks. All you can do is delete them and recreate them. However, there is a way of automating this process.

I had lots of photos on one disk and then moved them. The links to the files needed changing en masse and I didn't want to have to redo it by hand. What I needed was a way of finding out where the link *used* to point to and use that to construct the new link.

The answer was readlink. Thus:
#!/bin/bash
for fn in *.jpg; do
    NEWFN=$(readlink $fn | sed 's,/media/d1,/media/d2,')
    ln -sf $NEWFN $fn
done
Pipe the data from readlink into sed, which is used to replace an occurrence of the string /media/d1 with /media/d2. Then recreate the link, using the -f flag to delete an existing link.

Easy. Full credit to this post on SuperUser.

No comments:

Post a Comment

Your Host

Husband, father, pop music anorak, guitarist