繁体   English   中英

在bash脚本和awk命令中需要帮助

[英]Need help in bash script and awk command

我需要一个bash脚本来递归地打印文件夹名称和文件名(在stdo / p中)。 例如:我有一个文件夹结构,如/earth/plants/flowers/rose/rose.jpg。

/earth/plant/fruits/apple/apple.jpg.
/earth/animals/carni/lions.jpg
/earth/animals/herbi/omni/dog.jpg

现在我需要列出这样的文件和文件夹,我的意思是我的O / P脚本应该是,

planet=earth
category=animal (plant) 
sub cat = carni 
name = lion.jpg.

我试过了

`find / -name "*" -print | awk -F"/" '{ print "\n planet=",$2,"\n category=",$3,"\n sub cat=",$4,"\n Name=",$5, $6 }'`

上面的命令给了我以下O / P。

planet=earth 
category=animal (plant)  
sub cat = carni 
name = lion.jpg

但是在某些情况下,我还有其他文件夹,例如“ /earth/animals/herbi/omni/rabbit.jpg ”,在这种情况下,输出顺序会发生变化,例如:

planet=earth 
category=animal 
sub cat = herbi 
name = omni 
rabbit.jpg 

所以我需要在几个地方列出其他subcat。 喜欢

planet=earth
category=animals
sub cat = herbi
add cat = omni
name = rabbit.jpg

因此,如何使用单个脚本即可做到这一点。除了awk,还欢迎使用其他脚本。

`find / -name "*" -print | awk -F"/" '{ print "\n planet=",$2,"\n category=",$3,"\n sub cat=",$4,"\n Name=",$5,$6}``

在这种情况下,$ 5中的内容仅会作为名称打印。因此需要这样的东西。

 ``find / -name "*" -print | awk -F"/" '{ print "\n planet=",$2,"\n category=",$3,"\n sub cat=",$4,"\n add cat =",$5,(if $5 = foldername print  "add cat = omni")  name = $6 }'"``.

谢谢,vijai k

awk -F"/" '{
    print "\n planet=", $2, "\n category=", $3, "\n sub cat=", $4
    for (i = 5; i < NF; i++) print " add cat=", $i
    print " Name=",$NF
}'

您可以尝试以下方法-塞满了Bashisms,在其他shell中不起作用:

(查找命令在此处) | while IFS=/ read root planet category rest; do | while IFS=/ read root planet category rest; do

    echo "planet=$planet"
    echo "category=$category"
    size="$(stat -c %s "/$planet/$category/$rest")"
    while [[ "$rest" == */* ]]; do
       subcat="${rest%%/*}"
       rest="${rest#*/}"
       echo "subcategory=$subcat"
     done
     echo "name=$rest"
     echo "size=$size"
     echo
done

另外,在find命令上使用-name "*"是多余的。 但是您可能至少需要-type f

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM