Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to batch rename symlink targets?

Tags:

linux

shell

Something like rename does for files but for symlink targets.

So if I have

link1 -> /usr/share/lib-1.2.2/file1
link2 -> /usr/share/lib-1.2.2/file2

I could do

rename 1.2.2 2.0.3 link*

and have

link1 -> /usr/share/lib-2.0.3/file1
link2 -> /usr/share/lib-2.0.3/file2
like image 801
Jan Matějka Avatar asked Jul 12 '12 16:07

Jan Matějka


People also ask

How do you rename all files in a folder at once in Unix?

Rename Multiple Files with the mv Command On its own, the mv command renames a single file. However, combining it with other commands allows you to rename multiple files at the same time. Using this syntax, the find command defines an element of the current file name as the search parameter.


2 Answers

Use this script:

#!/bin/sh
from="$1"
to="$2"
shift 2
for i
do
  a=$(readlink "$i") && ln -sf "$(echo $a | sed "s@$from@$to@")" "$i"
done

Usage example:

$ ls -l
total 0
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 1 -> /bin/1
lrwxrwxrwx 1 igor igor 7 Jul 12 18:56 10 -> /bin/10
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 2 -> /bin/2
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 3 -> /bin/3
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 4 -> /bin/4
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 5 -> /bin/5
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 6 -> /bin/6
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 7 -> /bin/7
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 8 -> /bin/8
lrwxrwxrwx 1 igor igor 6 Jul 12 18:56 9 -> /bin/9
<links>$ bash ../rename-links /bin/ /usr/bin/ *
<links>$ ls -l
total 0
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 1 -> /usr/bin/1
lrwxrwxrwx 1 igor igor 11 Jul 12 18:57 10 -> /usr/bin/10
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 2 -> /usr/bin/2
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 3 -> /usr/bin/3
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 4 -> /usr/bin/4
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 5 -> /usr/bin/5
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 6 -> /usr/bin/6
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 7 -> /usr/bin/7
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 8 -> /usr/bin/8
lrwxrwxrwx 1 igor igor 10 Jul 12 18:57 9 -> /usr/bin/9
like image 105
Igor Chubin Avatar answered Sep 30 '22 19:09

Igor Chubin


util-linux-2.23

rename(1):
  - supports new command line option --symlink to rename symlink target
like image 32
Jan Matějka Avatar answered Sep 30 '22 20:09

Jan Matějka