我有很多相对符号链接,我想转移到另一个目录。
如何在保留正确路径的同时移动符号链接(具有相对路径的链接)?
答案 0 :(得分:28)
您可以使用readlink -f foo
将相对路径转换为完整路径。所以你会做类似的事情:
ln -s $(readlink -f $origlink) $newlink
rm $origlink
编辑:
我注意到你希望保持相对路径。在这种情况下,移动链接后,可以使用symlinks -c
将绝对路径转换回相对路径。
答案 1 :(得分:8)
这是保留相对路径的perl
解决方案:
use strictures;
use File::Copy qw(mv);
use Getopt::Long qw(GetOptions);
use Path::Class qw(file);
use autodie qw(:all GetOptions mv);
my $target;
GetOptions('target-directory=s' => \$target);
die "$0 -t target_dir symlink1 symlink2 symlink3\n" unless $target && -d $target;
for (@ARGV) {
unless (-l $_) {
warn "$_ is not a symlink\n";
next;
}
my $newlink = file(readlink $_)->relative($target)->stringify;
unlink $_;
symlink $newlink, $_;
mv $_, $target;
}
答案 2 :(得分:2)
可以使用tar
移动包含相对符号链接的文件夹。
例如:
cd folder_to_move/..
tar czvf files.tgz folder_to_move
cd dest_folder/..
tar xzvf /absolute/path/to/folder_to_move/../files.tgz
# If all is fine, clean-up
rm /absolute/path/to/folder_to_move/../files.tgz
rm -rf /absolute/path/to/folder_to_move
答案 3 :(得分:0)
改善Christopher Neylan的答案:
~/bin $ cat mv_ln
#!/bin/bash
#
# inspired by https://stackoverflow.com/questions/8523159/how-do-i-move-a-relative-symbolic-link#8523293
# by Christopher Neylan
help() {
echo 'usage: mv_ln src_ln dest_dir'
echo ' mv_ln --help'
echo
echo ' Move the symbolic link src_ln into dest_dir while'
echo ' keeping it relative'
exit 1
}
[ "$1" == "--help" ] || [ ! -L "$1" ] || [ ! -d "$2" ] && help
set -e # exit on error
orig_link="$1"
orig_name=$( basename "$orig_link" )
orig_dest=$( readlink -f "$orig_link" )
dest_dir="$2"
ln -r -s "$orig_dest" "$dest_dir/$orig_name"
rm "$orig_link"
的一部分
答案 4 :(得分:0)
当然使用ln
:
for i in *; do # or whatever pattern you're wanting to match
ln -sr "$(readlink "$i")" newdir/"$i";
done;
我很惊讶这能奏效,但 LN(1)
必须足够聪明才能注意到正在发生的事情并帮助您!我什至尝试使用 ../somethingelse
的“newdir”(在链接重写中应该是无操作)和 ..
(这将从链接目标中删除 ..
),而且效果很好。