3

I need to move some directories and make symlinks back to them.

The directory structure looks like:

/storage1
/storage1/123/named_directory_1
/storage1/123456/named_directory_2
/storage1/123456789/named_directory_3

I want to move the named directories, to matching numbered directories elsewhere, like so:

/storage2
/storage2/123/named_directory_1
/storage2/123456/named_directory_2
/storage2/123456789/named_directory_3

and then symlink those named directories back. the numbered directories remain as independent directories on each storage, but the named directories should be symlinked from their respective numbered directories on storage1 to the matching numbered directory on storage2.

i worked up a find command that matches what I want: find . -type d -mindepth 2 -maxdepth 2 -regextype grep -regex ".*/[0-9]\{1,10\}/.*" which matches all of these:

/storage2/123/named_directory_1
/storage2/123456/named_directory_2
/storage2/123456789/named_directory_3

but I don't know how to do all the manipulations. something like this, but you can see i have no idea how to get $number and $numberandname... but I have been experiementing with BASH parameters and substitutions but I can't quite get it right.

echo "${named#*/}"
named_directory_1

and this one:

echo "${named%/*}"
/storage/123

here is my best script outline:

while read -r named; do
export numberandname="${named#/*/*/*/}"
export number="${numberandname%/*}"
    mv -- "$named" "/storage2/$number/"
    ln -s -- "/storage2/$numberandname "$named"
done < <(find /storage1/ -type d -mindepth 2 -maxdepth 2 -regextype grep -regex ".*/[0-9]\{1,10\}/.*")
1

I was add some improvements (in my opinion) to your code.

1) I was used -printf '%P\n' option for find command and this gave path without storage1 part.
2) Removed export commands, because it doesn't needed here.

#!/bin/bash

src_dir="storage1"
dest_dir="storage2"    

nums_and_names=$(find "$src_dir" -type d -mindepth 2 -maxdepth 2 -regextype grep -regex ".*/[0-9]\{1,10\}/.*" -printf '%P\n')

while read -r named; do
    echo mv -- "${src_dir}/$named" "${dest_dir}/${named%/*}"
    echo ln -s -- "${dest_dir}/$named" "${src_dir}/$named" 
done <<< "$nums_and_names"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.