How to use bash to display folders with two subfolders?

I use bash through Cygwin. I have a large folder (a) with many subfolders (b). These subfolders have one or two subfolders each (s). I want to find all subfolders (b) that have two subfolders (c) and display them.

The structure is as follows:

a b1 c1 b2 c1 c2 b3 c1 c2 

So far, I only know how to use find and pipe to list all subfolders in the main folder (a).

 find . -type d > folders.txt 

How can I output only all b folders with two folders c to a text file with one folder per line? (In my example, the output should be:

 b2 b3 
+4
source share
4 answers

Try this with :

 cd a find . -type d | awk -F/ '{arr[$2]++}END{for (a in arr) {if (arr[a] == 3) print a}}' 

Or using :

 cd a for i in */; do x=( $i/*/ ); (( ${#x[@]} == 2 )) && echo "${i%/}"; done 
+4
source

There is a much simpler solution that uses the fact that the parent directory .. refers to each subdirectory, increasing the number of links in the directory by 1. In a directory without subdirectories there is a link with number 2 ( . And a link from its own parent by name) . Thus, a directory with two subdirectories has 4 links:

 find . -type d -links 4 

You cannot make other hard links in the directory so that there are no false positives.

+3
source

There is an awesome open source utility that will do what you want. It is called a β€œtree,” and it has many useful options. It is included in most Linux distributions, but you must compile Cygwin.

You can find the "tree" at: http://mama.indstate.edu/users/ice/tree/

You can also use Perl. It would be more flexible than a Bash script shell. Use the File :: Find module in Perl ( http://perldoc.perl.org/File/Find.html ), which allows you to easily do what you want. Do you have Perl installed in Cygwin? Do you know perl Let me know if you want me to publish a Perl script to do this.

0
source

Try running a bash script -

 #!/bin/bash cd a for i in `pwd`/* ; do if [ -d "$i" ]; then DIR=0; cd $i; for j in * ; do if [ -d "$j" ]; then let DIR=DIR+1; fi done if [ $DIR -eq 2 ]; then echo $i; fi fi done 

Suppose the script name is test.sh , you can do

 $./test.sh > folder.txt 
0
source

All Articles