將符號連結替換為目標

將符號連結替換為目標

如何在 Mac OS X 上將目錄(及其子目錄)中的所有符號連結替換為其目標?如果目標不可用,我寧願保留軟連結。

答案1

如果您使用 mac OSX 別名,則find . -type l不會出現任何內容。

您可以使用以下 [Node.js] 腳本將符號連結的目標移動/複製到另一個目錄:

fs = require('fs')
path = require('path')

sourcePath = 'the path that contains the symlinks'
targetPath = 'the path that contains the targets'
outPath = 'the path that you want the targets to be moved to'

fs.readdir sourcePath, (err,sourceFiles) ->
    throw err if err

    fs.readdir targetPath, (err,targetFiles) ->
        throw err if err

        for sourceFile in sourceFiles
            if sourceFile in targetFiles
                targetFilePath = path.join(targetPath,sourceFile)
                outFilePath = path.join(outPath,sourceFile)

                console.log """
                    Moving: #{targetFilePath}
                        to: #{outFilePath}
                    """
                fs.renameSync(targetFilePath,outFilePath)

                # if you don't want them oved, you can use fs.cpSync instead

答案2

以下是以下版本奇米的readlink如果任何檔案名稱中有空格,則使用並將正常工作的答案:

新檔案名稱等於舊連結名稱:

find . -type l | while read -r link
do 
    target=$(readlink "$link")
    if [ -e "$target" ]
    then
        rm "$link" && cp "$target" "$link" || echo "ERROR: Unable to change $link to $target"
    else
        # remove the ": # " from the following line to enable the error message
        : # echo "ERROR: Broken symlink"
    fi
done

新檔名等於目標名稱:

find . -type l | while read -r link
do
    target=$(readlink "$link")
    # using readlink here along with the extra test in the if prevents
    # attempts to copy files on top of themselves
    new=$(readlink -f "$(dirname "$link")/$(basename "$target")")
    if [ -e "$target" -a "$new" != "$target" ]
    then
        rm "$link" && cp "$target" "$new" || echo "ERROR: Unable to change $link to $new"
    else
        # remove the ": # " from the following line to enable the error message
        : # echo "ERROR: Broken symlink or destination file already exists"
    fi
done

答案3

您沒有說明替換後文件應具有什麼名稱。

該腳本認為替換的連結應具有與連結相同的名稱。

for link in `find . -type l`
do 
  target=`\ls -ld $link | sed 's/^.* -> \(.*\)/\1/'`
  test -e "$target" && (rm "$link"; cp "$target" "$link")
done

如果您希望文件與目標具有相同的名稱,則應該這樣做。

for link in `find . -type l`
do
  target=`\ls -ld $link | sed 's/^.* -> \(.*\)/\1/'`
  test -e "$target" && (rm $link; cp "$target" `dirname "$link"`/`basename "$target"`)
done

相關內容