bash等同于Python的os.path.normpath?

| bash等于
os.path.normpath
是什么?我特别想删除执行
find
时给出的前导
./
。 matt @ stanley:〜/ src / libtelnet-0.20 / test $找到 。 ./Makefile ./Makefile.in ./Makefile.am ...     
已邀请:
        好吧,为此,您只需将输出通过ѭ3进行传递,就不必标准化整个路径:
your_command_goes_here | sed \'s?^\\./??\'
这将消除行首的所有
./
序列。 以下记录显示了此操作:
pax$ find -name \'qq*sh\'
./qq.ksh
./qq.sh
./qq.zsh
./qq2.sh
./qq2.zsh
./qqq/qq.sh

pax$ find -name \'qq*sh\' | sed \'s?^./??\'
qq.ksh
qq.sh
qq.zsh
qq2.sh
qq2.zsh
qqq/qq.sh
如您所见,我对我的临时shell脚本有一个相当直观的命名标准:-)     
        我正在努力寻找想使用
os.path.normpath
的情况。在具有符号链接的系统(例如UNIX或Windows)上,它返回的值可能未指定相同的文件:
$ mkdir /tmp/one /tmp/one/two
$ ln -s /tmp/one/two /tmp/foo
$ python -c \'import os.path; print os.path.normpath(\"/tmp/foo/..\")\'
/tmp
$ ls /tmp/foo/..
two
/tmp/foo/..
/tmp/one
,而不是
/tmp
! 在Linux上,“ 12”规范化路径中的所有符号链接。在执行命令时,它返回的文件名与
$filename
相同(如果以后涉及的符号链接之一被更改,则可能不会)。但是在大多数情况下,这不是必需的:只需保持
$filename
不变即可。 如果出于美观原因要删除“ 1”前缀,请专门去除它。
filename=${filename#./}
find | sed -e \'s!^\\./!!\'
    
        我通常通过使用
find
\的
-printf
参数来执行此操作。 如果您要在多个路径中进行搜索,则可以使用以下命令:
find path1 path2
如果您在
.
中进行搜索,则可以正常工作:
find -printf \'%P\\n\'
如果您使用混合路径(例如
find path1 path2 .
),则必须使用
sed
。     
        怎么样:
newpath=`echo -n \"$oldpath\" | python -c \'import sys, os; print os.path.normpath(sys.stdin.readline())\'`
? 我认为没有内置的bash函数可以完成Python的ѭ25的所有工作。最好准确描述要执行的转换。     
        这样写:
normpath() {
    [[ -z \"$1\" ]] && return

    local skip=0 p o c

    p=\"$1\"
    # check if we have absolute path and if not make it absolute
    [[ \"${p:0:1}\" != \"/\" ]] && p=\"$PWD/$p\"

    o=\"\"
    # loop on processing all path elements
    while [[ \"$p\" != \"/\" ]]; do
        # retrive current path element
        c=\"$(basename \"$p\")\"
        # shink our path on one(current) element
        p=\"$(dirname \"$p\")\"

        # basename/dirname correct handle multimple \"/\" chars
        # so we can not warry about them

        # skip elements \"/./\" 
        [[ \"$c\" == \".\" ]] && continue
        if [[ \"$c\" == \"..\" ]]; then
            # if we have point on parent dir, we must skip next element
            # in other words \"a/abc/../c\" must become \"a/c\"
            let \"skip += 1\"
        elif [[ 0 -lt $skip ]]; then
            # skip current element and decrease skip counter
            let \"skip -= 1\"
        else
            # this is normal element and we must add it to result
            [[ -n \"$o\" ]] && o=\"/$o\"
            o=\"$c$o\"
        fi
    done

    # last thing - restore original absolute path sign
    echo \"/$o\"
}
    
        这里可能重复。但是,如果您只想剥离领导者。//
find -type f | sed \'s/^\\.\\///\'
    
        我找到了:叫
realpath
! 输入类似的内容:
realpath ..   # the most interesting thing
要么
realpath .    # equivalent to `pwd\' and to `echo $PWD\'
享受! 与
os.path.normpath
不同,
realpath
需要路径存在。如果只想将其标准化为字符串
realpath -m
,则可以使用。     

要回复问题请先登录注册