简体   繁体   中英

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. 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 )

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?? should be the symlink's destination from the file and ??B?? should be the name of the file with the suffix _temp appended.

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. The shell itself is necessary because you cannot directly pass multiple commands to xargs .

The -print0 and corresponding xargs -0 are a GNU extension to correctly cope with tricky file names. See the find manual for details.

I would perhaps add a simple verification check before proceeding with the symlinking; for example, if grep -cm2 . on the file returns 2, skip the file (it contains more than one line of text). If you can be more specific (say, all the symlinks begin with ../ ) by all means be more specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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