0

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

2 Answers 2

5
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
}'
Sign up to request clarification or add additional context in comments.

4 Comments

Need one more help,if i want to display the size of $NF,what should i do ?
@vijai: To print the length in characters: print length($NF)
it is showing character count.ex.rabbit.jpg contains 10 chars,so it displaying 10. i need size of that file to printed.like 10kb.
@vijai: in AWK? system("stat -c %s " $NF) if your system has stat. Another way: system("wc -c <" $NF)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.