击:摆脱路径的所有路径(Bash: get all paths from path)

2019-10-20 19:01发布

说我有路径gui/site/junior/profile.py

我如何获得这个?:

gui
gui/site
gui/site/junior

奖金,如果你告诉我如何遍历每个路径:d

Answer 1:

你可以循环使用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 ,其计算当前记录多少场了。 在此基础上,从第一循环到最后一个,先打印每次到那个价值。



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


Answer 3:

您可以使用shell的内置分裂设施。 IFS指定拆就什么。

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

这可以在许多方面进行重构,但我想改变IFS只治理的实际分裂。

采用set到一个字符串分割成位置参数稍有模糊,但非常值得了解。

你应该好好的照顾到没有设置IFS ,如果它本来没有设置,但我克扣上。



Answer 4:

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==


文章来源: Bash: get all paths from path