Skip to content

Instantly share code, notes, and snippets.

@ErykDarnowski
Created August 24, 2023 16:10
Show Gist options
  • Save ErykDarnowski/d57b6e35cea53e1913d65d3dfadfb271 to your computer and use it in GitHub Desktop.
Save ErykDarnowski/d57b6e35cea53e1913d65d3dfadfb271 to your computer and use it in GitHub Desktop.
Find non-empty folders containing `Games` in their name, print their amount of children and sort the output by number

Find non-empty folders containing Games in their name, print their amount of children and sort the output by number

find -type d -name "*Games*" -not -empty

This part of the command uses the find command to search for directories (-type d) that have "Games" in their name (-name "Games") and are not empty (-not -empty). The find command prints the path of each matching directory to the standard output.

-exec sh -c 'echo "{}: $(expr $(ls -l "{}" | wc -l) - 1)"' \;

This part of the command uses the -exec option of the find command to execute another command on each matching directory. The command to execute is enclosed in single quotes and has a placeholder {} for the directory name. The command ends with a semicolon, which is escaped with a backslash to prevent the shell from interpreting it.

The command to execute is:

echo "{}: $(expr $(ls -l "{}" | wc -l) - 1)"

This command uses the echo command to print the directory name ({}) followed by a colon and a space. Then, it uses the expr command to evaluate an arithmetic expression, which is enclosed in parentheses and preceded by a dollar sign. The expression is:

$(ls -l "{}" | wc -l) - 1

This expression uses the ls command to list the files and sub-directories in the directory ({}) in long format (-l). The output of the ls command is piped to the wc command, which counts the number of lines in the input (-l). This gives the number of files and sub-directories in the directory. Then, 1 is subtracted from this number to get the number of sub-directories only.

| sort -n -k2

This part of the command uses the pipe symbol (|) to redirect the output of the previous command to another command, which is:

sort -n -k2

This command uses the sort command to sort the input lines according to some criteria. The -n option tells the sort command to sort numerically, rather than alphabetically. The -k2 option tells the sort command to sort by the second field in each line, which is separated by whitespace from the first field. The second field is the number of sub-directories in each directory.

The final output of the whole command is a list of directories that contain "Games" and are not empty, along with their number of sub-directories minus 1, sorted by this number in ascending order.

*Done with help of Bing AI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment