首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bash PWD缩短

Bash PWD缩短
EN

Stack Overflow用户
提问于 2009-10-24 09:23:46
回答 7查看 12.2K关注 0票数 22

我正在寻找一个bash函数,它可以缩短长路径名,以防止我的PS1变量变得过长。大致是这样的:

代码语言:javascript
复制
/this/is/the/path/to/a/really/long/directory/i/would/like/shortened

可能会以如下方式结束:

代码语言:javascript
复制
/t../i../t../p../to/a/r../l../d../i/w../like/shortened

采用路径和最大可接受字符数来缩短的内容对于我的.bashrc文件来说将是完美的。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-10-24 10:51:11

Python脚本怎么样?这将首先缩短最长的目录名,一次缩短一个字符,直到它达到其长度目标,或者无法使路径更短。它不会缩短路径中的最后一个目录。

(我一开始是用普通的shell脚本编写这段代码,但是bash在字符串操作方面很糟糕。)

代码语言:javascript
复制
#!/usr/bin/env python
import sys

try:
    path   = sys.argv[1]
    length = int(sys.argv[2])
except:
    print >>sys.stderr, "Usage: $0 <path> <length>"
    sys.exit(1)

while len(path) > length:
    dirs = path.split("/");

    # Find the longest directory in the path.
    max_index  = -1
    max_length = 3

    for i in range(len(dirs) - 1):
        if len(dirs[i]) > max_length:
            max_index  = i
            max_length = len(dirs[i])

    # Shorten it by one character.    
    if max_index >= 0:
        dirs[max_index] = dirs[max_index][:max_length-3] + ".."
        path = "/".join(dirs)

    # Didn't find anything to shorten. This is as good as it gets.
    else:
        break

print path

输出示例:

代码语言:javascript
复制
$ echo $DIR
/this/is/the/path/to/a/really/long/directory/i/would/like/shortened
$ ./shorten.py $DIR 70
/this/is/the/path/to/a/really/long/directory/i/would/like/shortened 
$ ./shorten.py $DIR 65
/this/is/the/path/to/a/really/long/direc../i/would/like/shortened
$ ./shorten.py $DIR 60
/this/is/the/path/to/a/re../long/di../i/would/like/shortened
$ ./shorten.py $DIR 55
/t../is/the/p../to/a/r../l../di../i/wo../like/shortened
$ ./shorten.py $DIR 50
/t../is/the/p../to/a/r../l../d../i/w../l../shortened
票数 5
EN

Stack Overflow用户

发布于 2009-10-25 01:46:36

没有给出相同的结果,但是我的~/.bashrc包含

代码语言:javascript
复制
_PS1 ()
{
    local PRE= NAME="$1" LENGTH="$2";
    [[ "$NAME" != "${NAME#$HOME/}" || -z "${NAME#$HOME}" ]] &&
        PRE+='~' NAME="${NAME#$HOME}" LENGTH=$[LENGTH-1];
    ((${#NAME}>$LENGTH)) && NAME="/...${NAME:$[${#NAME}-LENGTH+4]}";
    echo "$PRE$NAME"
}
PS1='\u@\h:$(_PS1 "$PWD" 20)\$ '

这将显示的路径限制为最多20个字符。如果路径超过20个字符,它将显示为/...d/like/shortened~/.../like/shortened

票数 35
EN

Stack Overflow用户

发布于 2009-10-24 13:22:21

这里有一个您可能会喜欢的bash解决方案。这会将路径的每个部分缩短到仍然可以用制表符完成的最短前缀,并使用*代替..。作为填充物。

代码语言:javascript
复制
#!/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.

将长度作为第一个参数,将路径作为可选的第二个参数。如果没有给出第二个参数,它将使用当前工作目录。

这将尝试缩短到给定的长度以下。如果这是不可能的,它只给出它能给出的最短路径。

从算法上讲,这可能很可怕,但它最终是相当快的。(快速shell脚本的关键是避免子shell和外部命令,尤其是在内部循环中。)

根据设计,它只能缩短2个或更多字符('hom*‘与’home‘的字符数相同)。

这并不完美。在某些情况下,它不会尽可能地缩短,比如如果有几个文件的文件名共享一个前缀(如果存在foobar1和foobar2,则不会缩短foobar3 )。

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1616678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档