I would use find to get the folder names, parse them with sed, grep the corresponding id and copy stuff over:
$ find . -mindepth 1 -type d | while read dir; do
id=$(echo "$dir" | sed 's/\.\/[[:alpha:]]*\([[:digit:]]*\)_[[:alnum:]]*/\1/');
new_name=$(grep -w "$id" names.csv | cut -d ';' -f 1);
mkdir -p "$new_name" && cpmv -rv "$dir"/* "$new_name"/ && rmdir "$dir";
done
The tricks are
- use
mkdir -pwhich will create the directory and exit silently if it exists. - use
grep -won the csv file to only get those lines that contain the entire ID bordered by non-word characters. That way you avoid matching both1123and123for the id123.