Oto bash-jedynym rozwiązaniem, które może chcesz . Skraca to każdą część ścieżki w dół do najkrótszego prefiksu, który nadal może być zakończony tabulatorem i używa * zamiast wypełnienia jako wypełniacza.
#!/bin/bash
begin="" # The unshortened beginning of the path.
shortbegin="" # The shortened beginning of the path.
current="" # The section of the path we're currently working on.
end="${2:-$(pwd)}/" # The unmodified rest of the path.
end="${end#/}" # Strip the first/
shortenedpath="$end" # The whole path, to check the length.
maxlength="${1:-0}"
shopt -q nullglob && NGV="-s" || NGV="-u" # Store the value for later.
shopt -s nullglob # Without this, anything that doesn't exist in the filesystem turns into */*/*/...
while [[ "$end" ]] && ((${#shortenedpath} > maxlength))
do
current="${end%%/*}" # everything before the first/
end="${end#*/}" # everything after the first/
shortcur="$current"
shortcurstar="$current" # No star if we don't shorten it.
for ((i=${#current}-2; i>=0; i--))
do
subcurrent="${current:0:i}"
matching=("$begin/$subcurrent"*) # Array of all files that start with $subcurrent.
((${#matching[*]} != 1)) && break # Stop shortening if more than one file matches.
shortcur="$subcurrent"
shortcurstar="$subcurrent*"
done
begin="$begin/$current"
shortbegin="$shortbegin/$shortcurstar"
shortenedpath="$shortbegin/$end"
done
shortenedpath="${shortenedpath%/}" # strip trailing/
shortenedpath="${shortenedpath#/}" # strip leading/
echo "/$shortenedpath" # Make sure it starts with/
shopt "$NGV" nullglob # Reset nullglob in case this is being used as a function.
Podaj długość jako pierwszy argument, a ścieżkę jako opcjonalny drugi argument. Jeśli nie podano drugiego argumentu, używa on bieżącego katalogu roboczego.
Spróbuje to skrócić do podanej długości. Jeśli nie jest to możliwe, daje tylko najkrótszą możliwą ścieżkę.
Pod względem algorytmicznym jest to prawdopodobnie okropne, ale kończy się dość szybko. (Kluczem do szybkich skryptów jest unikanie podpowłok i poleceń zewnętrznych, zwłaszcza w wewnętrznych pętlach).
Z założenia skraca się tylko o 2 lub więcej znaków ("hom *" to tyle samo znaków co "dom") .
To nie jest idealne. Są sytuacje, w których nie skróci się tak bardzo, jak to tylko możliwe, na przykład, jeśli istnieje kilka plików, których nazwy plików mają prefiks (jeśli istnieją foobar1 i foobar2, foobar3 nie zostanie skrócony).
Osobiście mam zachęcam po prostu do dwóch najwyższych katalogów, więc powyższe byłoby "li" ke/skrócony'. Używam ZSH, więc nie wiem, jak to zrobić w bash. – pavpanchekha
@pavpanchekha 'pwd | sed -e "s |. */\ (. * /. * \) | \ 1 |" ' – polypus74
I do użytku w PS1, można: funkcja pwd_depth_limit_2 { jeśli [" $ PWD "=" $ HOME "] następnie echo -n" ~ " else pwd | sed -e "s |. */\ (. * /. * \) | \ 1 |" fi } – polypus74