Need help in bash script and awk command

2020-05-09 02:04发布

问题:

I need a bash script to print folder names and file names recursively (in stdo/p). For example: i have a folders structure like /earth/plants/flowers/rose/rose.jpg.

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

now i need to list this files and folders like this i mean my O/P script should be,

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

i tried

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

above command gives me following O/P.

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

But in some cases i've additional folders like "/earth/animals/herbi/omni/rabbit.jpg" in this case order is changing in output like:

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

so i need to list additional subcat in few places . like

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

so how to do that with a single script.Scripts apart from awk is also welcome.

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

in this case what ever there in $5 it will print as name only.so need something like this.

 ``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 }'"``.

thanks, vijai k

回答1:

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
}'


回答2:

You could try this - chock full of bashisms, won't work in other shells:

(find command goes here) | 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

Also, -name "*" on a find command is redundant. But you probably want -type f at least.



标签: linux bash awk