1

Windows and tools running on windows servers (eg. OneDrive) have a limit on path lengths.

I am looking for a command line tool in OSX/Linux/Unix to, within a directory, shorten all paths above a path length threshold, for example, by keeping the first 5 characters and the last 5 characters of each folder/file name in overly long paths, starting with the names of folders and files most distant from the root (ie. most nested).

ie

folder_very_very_long_name/folder_very_very_long_name/folder_very_very_long_name/file_very_very_long_name

could become

folder_very_very_long_name/folder_very_very_long_name/folde_name/file__name

I can already identify the troublesome paths using:

find . -name \* -type f | perl -ne 's/(.*)/print length($1), " $1\n"/e' | sort -nu

from:

https://discussions.apple.com/thread/2590442?tstart=0

  • What do you want to happen if folder_very_very_long_name/folder_very_very_long_name/folde_name/file__name already exists? – Andrew Morton Jul 25 '16 at 19:03
1
lp="folder_very_very_long_name/folder_very_very_long_name/folder_very_very_long_name/file_very_very_long_name"

IFS='/' read -a components <<< "$lp"

combined_path=""

for comp in "${!components[@]}"
do
    if [ ${#components[$comp]} -gt 0 ]; then
        a=$(echo ${components[$comp]} | cut -c -5);
        b=$(echo ${components[$comp]} | tail -r -c 6);
        if [ $comp -eq 0 ]; then
            combined_path="$a...$b"
        else
            combined_path="$combined_path/$a...$b"
        fi
    fi
done
echo $combined_path

Example Output:

folde..._name/folde..._name/folde..._name/file_..._name

Explanation:

IFSis your delimiter; you read in lp and store each part of your splitted string in the array components.

Then you iterate over each element in your array, using the if statement to check whether the respective comp is empty, thus indicating a path beginning at root. Using cut you get the first 5 characters and using tail the last 5. You then append that to your overall path combined_path, concatenating a and b with ... between the two. (That's just to make the shortening more visible and can easily be left out).

Hope this helps you getting closer to your desired solution.

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.