如何使用bash返回设定点后的所有路径

时间:2014-12-12 18:06:36

标签: bash

我要回复:

./nas/cdn/catalog/swatches
./nas/cdn/catalog/product_shots
./nas/cdn/catalog/product_shots/high_res
./nas/cdn/catalog/product_shots/high_res/back
./nas/cdn/catalog/product_shots/high_res/front
./nas/cdn/catalog/product_shots/low_res
./nas/cdn/catalog/product_shots/low_res/back
./nas/cdn/catalog/product_shots/low_res/front
./nas/cdn/catalog/product_shots/thumbs
./nas/cdn/catalog/full_length
./nas/cdn/catalog/full_length/high_res
./nas/cdn/catalog/full_length/low_res
./nas/cdn/catalog/cropped
./nas/cdn/catalog/drawings

从中删除./nas/cdn/catalog/的正确方法是什么?

到目前为止,这是我的代码

BASE='./nas/cdn/catalog'
echo $BASE
for d in $(find . -type d -regex "${BASE}/[^.]*")
do
    echo $(basename $d)

done

这只是返回最后一个文件夹,我想返回/ swatches,/ product_shots / high_res等......

2 个答案:

答案 0 :(得分:1)

使用sed,如下所示,

BASE='./nas/cdn/catalog'
echo $BASE
for d in $(find . -type d -regex "${BASE}/[^.]*")
do
    sed 's~^\([^/]*/\)\{4\}~~' <<< "$d"
done

示例:

$ var="./nas/cdn/catalog/drawings"
$ sed 's~^\([^/]*/\)\{4\}~~' <<< "$var"
drawings

答案 1 :(得分:1)

一种稍微简单的方法:

BASE='./nas/cdn/catalog'
echo "$BASE"
( cd "$BASE" ; find */ -type d )

注意:这不是很完美;当$BASE内的任何目录以连字符开头时,它将失败。只有当你能保证不是这种情况时才应该使用它。