Search code examples
bashsymlinkbatch-rename

How to batch append subdirectory to link target in bash


I have a directory under my control with a lot of symbolic links to sub-directories in another directory not under my control. The "format" has recently changed, and I would like to update all my symbolic links to append "new" to the link target.

Example of the current situation:

  • u -> /catalog/uvw
  • v -> /catalog/uvw
  • x -> /catalog/xyz
  • y -> /catalog/xyz
  • ...

How can I batch-append a subdirectory to each link target, so that the new links have the following targets?

  • u -> /catalog/uvw/new
  • v -> /catalog/uvw/new
  • x -> /catalog/xyz/new
  • y -> /catalog/xyz/new
  • ...

Solution

  • Please try the following:

    find . -type l -maxdepth 1 -print0 | while IFS= read -r -d "" link; do
        target="$(readlink "$link")"
        ln -nfs "$target/new" "$link"
    done
    

    Hope this helps.