我需要重命名我的 Linux/Solaris 机器中的许多目录和文件。 有许多指向这些目录/文件的链接。
因此,首先我创建以下脚本以找到我想要重命名的所有目录(如 DOMAIN.city.country
、DOMAIN.type.country
等。 )
及其链接。
该脚本从文件 info.file
文件中获取节点的旧名称和新名称。每行的第一个字段代表旧目录名,第二个字段代表新目录名。
文件 find_and_recreate_link_to_new_dir.ksh
while read -r line ; do
[[ -z $line ]] && continue
name_old_dir=` echo $line | awk '{print $1}' `
name_new_dir=` echo $line | awk '{print $2}' `
find / -type l -exec ls -l 2>/dev/null '{}' \; | perl -ne'BEGIN { $str = shift(@ARGV); } print if /\Q$str\E/; ' $name_old_dir
done < /tmp/test/info.file
文件 /tmp/test/info.file
DOMAIN.city.country DOMAIN.world.country
DOMAIN.city1.country DOMAIN.world1.country
...
当我运行我的脚本时,我得到了这个输出
lrwxrwxrwx 1 root root 19 Mar 15 11:22 /var/test/info.domain2.com -> DOMAIN.city.country
lrwxrwxrwx 1 root root 19 Mar 15 11:22 /var/test/info.domain.com -> DOMAIN.city.country
lrwxrwxrwx 1 root root 19 Mar 15 11:22 /var/test/info.domain1.com -> DOMAIN.city.country
lrwxrwxrwx 1 root root 5 Mar 15 11:57 /var/test/DOMAIN.type.country -> mkdir
lrwxrwxrwx 1 root root 19 Mar 15 11:58 /var/test/info.tyep.com -> DOMAIN.type.country
...
现在我需要向该脚本添加一个部分,该部分将重新创建指向新目录的当前链接。例如
/var/test/info.domain2.com -> DOMAIN.world.country
请建议自动重新创建指向新目录的当前链接的最佳解决方案。
最佳答案
如果我正确理解了问题,您想根据来自 find_and_recreate_link_to_new_dir.ksh
的信息创建符号链接(symbolic link)。
如果你得到
lrwxrwxrwx 1 root root 19 Mar 15 11:22 /var/test/info.domain2.com -> DOMAIN.city.country
你会想要创建链接
/var/test/info.domain2.com -> DOMAIN.city.country
在这种情况下,我建议您存储这两个参数并使用它们调用 ln -s
。将数据保存在文件中可能很有趣,比方说 FILE_WITH_NEW_DATA:
find / -type l -exec ls -l 2>/dev/null '{}' \; | perl -ne'BEGIN { $str = shift(@ARGV); } print if /\Q$str\E/; ' $name_old_dir >> FILE_WITH_NEW_DATA
然后,给定字符串
lrwxrwxrwx 1 root root 19 Mar 15 11:22 /var/test/info.domain2.com -> DOMAIN.city.country
您可以通过以下方式获取参数:
link = $(awk 'N=NF-2 {print $N}')
file = $(awk '{print $NF}')
然后使用 ln -s $file $link
创建符号链接(symbolic link)。
一起,
...
find / -type l -exec ls -l 2>/dev/null '{}' \; | perl -ne'BEGIN { $str = shift(@ARGV); } print if /\Q$str\E/; ' $name_old_dir >> FILE_WITH_DATA
...
while read -r line ; do
[[ -z $line ]] && continue
link = $(echo $line | awk 'N=NF-2 {print $N}')
file = $(echo $line | awk '{print $NF}')
# begin OPTION 1) we delete previous link
rm $link
ln -s $file $link
# end OPTION 1)
# begin OPTION 2) we force the link to be created and replace the older one
ln -s -f $file $link
# end OPTION 2)
done < FILE_WITH_NEW_DATA
关于linux - 自动重新创建许多不同的链接到重命名的目录或文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15431785/