1

私には道があると言うgui/site/junior/profile.py

どうすれば入手できますか?:

gui
gui/site
gui/site/junior

各パスをループする方法を教えてくれればボーナス:D

4

4 に答える 4

2

シェルの組み込み分割機能を使用できます。IFS何を分割するかを指定します。

oldIFS=$IFS
IFS=/
set -f
set -- $path
set +f
IFS=$oldIFS
for component in "$@"; do
    echo "$component"
done

これはさまざまな方法でリファクタリングできますが、変更がIFS実際の分割のみを管理するようにしたいと考えています。

set文字列を位置パラメータに分割するための の使用は少しわかりにくいですが、知っておく価値は十分にあります。

もともと設定が解除されていた場合は、設定を解除するように適切に注意する必要がありますIFSが、私はそれを軽視しています。

于 2014-08-22T13:41:29.513 に答える
2

awk でループできます:

awk 'BEGIN{FS=OFS="/"}
     {  for (i=1; i<=NF; i++) {
           for (j=1; j<i; j++)
              printf "%s/", $j
           printf "%s\n", $i
        }
     }' <<< "gui/site/junior/profile.py"

ワンライナーとして見てください:

$ awk 'BEGIN{FS=OFS="/"}{for (i=1; i<=NF; i++) { for (j=1; j<i; j++) printf "%s%s", $j, OFS; printf "%s\n", $i}}' <<< "gui/site/junior/profile.py"
gui
gui/site
gui/site/junior
gui/site/junior/profile.py

これはNF、現在のレコードにあるフィールドの数をカウントする を利用します。それに基づいて、最初から最後の値までループし、最初にその値まで毎回印刷します。

于 2014-08-22T12:31:22.817 に答える
2

ダッシュの答え:

path="gui/site with spaces/junior/profile.py"
oldIFS=$IFS
IFS=/
set -- $(dirname "$path")
IFS=$oldIFS
accumulated=""
for dir in "$@"; do 
  accumulated="${accumulated}${dir}/"
  echo "$accumulated"
done
gui/
gui/site with spaces/
gui/site with spaces/junior/
于 2014-08-22T13:43:57.197 に答える
1

Perl バリアント:

perl -F/ -nlE 'say join("/",@F[0..$_])||"/"for(0..$#F-1)' <<< "gui/site with spaces/junior/profile.py"

生産する

gui
gui/site with spaces
gui/site with spaces/junior

NULL 区切りのパス名がある場合は、0引数に追加できます。

perl -F/ -0nlE 'say join("/",@F[0..$_])||"/"for(0..$#F-1)'
          ^

例えばから

printf "/some/path/name/here/file.py\0" |  perl -F/ -nlE 'say join("/",@F[0..$_])||"/"for(0..$#F-1)'
#                                   ^^

生産する

/
/some
/some/path
/some/path/name
/some/path/name/here

パスを反復するには、次を使用できます。

origpath="some/long/path/here/py.py"

do_something() {
        local path="$1"
        #add here what you need to do with the partial path
        echo "Do something here with the ==$path=="
}

while read -r part
do
        do_something "$part"
done < <(perl -F/ -nlE 'say join("/",@F[0..$_])||"/"for(0..$#F-1)' <<< "$origpath")

それは生成します:

Do something here with the ==some==
Do something here with the ==some/long==
Do something here with the ==some/long/path==
Do something here with the ==some/long/path/here==
于 2014-08-22T13:24:40.237 に答える