简体   繁体   English

从文件内容创建符号链接

[英]Create symlink from the contents of a file

Due to an inefficient workflow where I have to copy directories between a Linux machine and a windows machine. 由于工作流程效率低下,我不得不在Linux机器和Windows机器之间复制目录。 The directories contain symlinks which (after copying Linux>Windows>Linux) contain the link in plaintext (eg foobar.C contains the text ../../../Foo/Bar/foobar.C ) 目录包含符号链接,这些符号链接(在复制Linux> Windows> Linux之后)包含纯文本链接(例如foobar.C包含文本../../../Foo/Bar/foobar.C

Is there an efficient way to recreate the symlinks from the contents of the file recursively for a complete directory? 有没有一种有效的方法可以从文件的内容中递归地重新创建符号链接,以获得完整的目录?

I have tried: 我努力了:

find . | xargs ln -s ??A?? ??B?? && mv ??B?? ??A??

where I really have no idea how to populate the variables, but ??A?? 我真的不知道如何填充变量,但是??A?? should be the symlink's destination from the file and ??B?? 应该是文件和符号“ ??B?? ”中符号链接的目标。 should be the name of the file with the suffix _temp appended. 应该是后缀_temp的文件名。

If you are certain that all the files contain a symlink, it's not very hard. 如果您确定所有文件都包含符号链接,那不是很难。

find . -print0 | xargs -r 0 sh -c '
 for f; do ln -s "$(cat "$f")" "${f}_temp" && mv "${f}_temp" "$f"; done' _

The _ dummy argument is necessary because the second argument to sh -c is used to populate $0 in the subshell. _ dummy参数是必需的,因为sh -c的第二个参数用于在子shell中填充$0 The shell itself is necessary because you cannot directly pass multiple commands to xargs . Shell本身是必需的,因为您不能直接将多个命令传递给xargs

The -print0 and corresponding xargs -0 are a GNU extension to correctly cope with tricky file names. -print0和相应的xargs -0是GNU扩展,可以正确处理棘手的文件名。 See the find manual for details. 有关详细信息,请参见find手册。

I would perhaps add a simple verification check before proceeding with the symlinking; 在进行符号链接之前,我可能会添加一个简单的验证检查; for example, if grep -cm2 . 例如,如果grep -cm2 . on the file returns 2, skip the file (it contains more than one line of text). 在文件返回2时,跳过文件(它包含多行文本)。 If you can be more specific (say, all the symlinks begin with ../ ) by all means be more specific. 如果可以更具体(例如,所有符号链接都以../开头),则一定要更具体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM