Bash equivalent of Python os.path.normpath?

What does bash equivalent mean os.path.normpath? In particular, I am interested in deleting the master ./given at runtime find.

matt @ stanley : ~ / src / libtelnet-0.20 / test $ find
.
./Makefile
./Makefile.in
./Makefile.am
...
+5
source share
7 answers

Well, for this you can simply pass the output through sed, you do not need to normalize the whole path:

your_command_goes_here | sed 's?^\./??'

This will save you all the ./sequences at the beginning of the line.

The following decryption shows this in action:

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

, : -)

+2

, 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 readlink -- "$filename" . , , , $filename ( ). : $filename .

./ , .

filename=${filename#./}
find | sed -e 's!^\./!!'
+2

find -printf.

, :

find path1 path2

, .:

find -printf '%P\n'

(, find path1 path2 .), sed.

+1

:

newpath=`echo -n "$oldpath" | python -c 'import sys, os; print os.path.normpath(sys.stdin.readline())'`

?

, bash, , Python normpath. , , .

+1

- :

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"
}
+1

. , ./

find -type f | sed 's/^\.\///'
0

: realpath! - :

realpath ..   # the most interesting thing

realpath .    # equivalent to `pwd' and to `echo $PWD'

!

0

All Articles