Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print all the parent directories in Bash

I have a text file containing some directories.

For example

./dir1/dir2/dir3
./dir4/dir5

And I want to end up with a file text with the list of all the subdirectories :

.
./dir1
./dir1/dir2
./dir1/dir2/dir3
./dir4
./dir4/dir5

I tried this way but it won't work

cat folders_recently_used | xargs -I {} sh -c 'TEST={} ;
     while true; 
     do dirname $TEST; 
          if [ $(dirname $TEST) == '.' ]; 
             then break ; 
             else $TEST = $(dirname $TEST);
          fi  ; done' > folders_to_use
like image 264
Antoine Xevlabs Avatar asked Oct 16 '25 22:10

Antoine Xevlabs


2 Answers

Here's another way using a bash array and no external child processes:

#!/bin/bash

while IFS='/' read -a path
do
    prefix=""
    for ((i=0; i < ${#path[@]}; i++))
    do
        echo "$prefix${path[i]}"
        prefix="$prefix${path[i]}/"
    done
done < folders_recently_used

For the supplied example data, this gives:

.
./dir1
./dir1/dir2
./dir1/dir2/dir3
.
./dir4
./dir4/dir5

The IFS='/' makes the Internal Field Separator the / character so that it splits the string on the /. read -a reads one field into each element of an array, in this case the array is called path.

for ((i=0; i < ${#path[@]}; i++)) iterates through the array indexes (i). ${#path[@]} gives the number of elements in the array, in this case that is the number of directories in the path.

The rest is just string concatenation.

like image 137
cdarke Avatar answered Oct 18 '25 14:10

cdarke


File:

$ cat subdirs
./dir1/dir2/dir3
./dir4/dir5

Script (ugly a bit, but works fine):

#!/bin/bash

while read line
do
    counter=$(echo "${line}" | grep -o '/' | wc -l)
    i=1
    j=$(($i + 1))
    echo "Original string: ${line}"
    echo "Its parent directories:"
    while [ "${counter}" -gt 0 ]
    do
            echo "${line}" | cut -d'/' -f$i-$j
            counter=$(($counter - 1))
            j=$(($j + 1))
    done
    echo "Next one if exists..."
    echo ""
done < subdirs

Output:

Original string: ./dir1/dir2/dir3
Its parent directories:
./dir1
./dir1/dir2
./dir1/dir2/dir3
Next one if exists...

Original string: ./dir4/dir5
Its parent directories:
./dir4
./dir4/dir5
Next one if exists...
like image 23
Viktor Khilin Avatar answered Oct 18 '25 14:10

Viktor Khilin