巴什PWD缩短 [英] Bash PWD Shortening

查看:114
本文介绍了巴什PWD缩短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一个bash的功能,这将缩短长路径名来保持我的PS1变量从得到过长。沿着线的东西:

I'm looking for a bash function that will shorten long path names to keep my PS1 variable from getting excessively long. Something along the lines of:

/this/is/the/path/to/a/really/long/directory/i/would/like/shortened

可能最终为:

/t../i../t../p../to/a/r../l../d../i/w../like/shortened

东西,拿了路径和字符的最大可接受数缩短将是完美的我.bashrc文件。

something that the took the path and a maximum acceptable number of characters to shorten to would be perfect for my .bashrc file.

推荐答案

如何Python脚本?这将缩短第一最长的目录名,在直到它符合其长度的目标或无法获得任何路径短一个字符。它不会缩短最后的目录的路径。

How about a Python script? This shortens the longest directory names first, one character at a time until it meets its length goal or cannot get the path any shorter. It does not shorten the last directory in the path.

(我开始在普通的shell脚本,而是人写这个,庆典太臭在字符串操作。)

(I started writing this in plain shell script but man, bash stinks at string manipulation.)

!/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

输出示例:

$ 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

这篇关于巴什PWD缩短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆