How to resolve the algorithm Walk a directory/Recursively step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Walk a directory/Recursively step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

Walk a given directory tree and print files matching a given pattern.

Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory.

Note: Please be careful when running any code examples found here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Walk a directory/Recursively step by step in the UNIX Shell programming language

Source code in the unix programming language

find . -name '*.txt' -type f


#! /bin/bash
# Warning: globstar excludes hidden directories.
# Turn on recursive globbing (in this script) or exit if the option is not supported:
shopt -s globstar || exit

for f in **
do
  if [[ "$f" =~ \.txt$ ]] ; then
    echo "$f"
  fi
done


#! /bin/bash

indent_print()
{
    for((i=0; i < $1; i++)); do
	echo -ne "\t"
    done
    echo "$2"
}

walk_tree()
{
    local oldifs bn lev pr pmat
    if [[ $# -lt 3 ]]; then
	if [[ $# -lt 2 ]]; then
	    pmat=".*"
	else
	    pmat="$2"
	fi
	walk_tree "$1" "$pmat" 0
	return
    fi
    lev=$3
    [ -d "$1" ] || return
    oldifs=$IFS
    IFS="
"
    for el in $1/*; do
	bn=$(basename "$el")
	if [[ -d "$el" ]]; then
	    indent_print $lev "$bn/"
	    pr=$( walk_tree "$el" "$2" $(( lev + 1)) )
	    echo "$pr"
	else
	    if [[ "$bn" =~ $2 ]]; then
		indent_print $lev "$bn"
	    fi
	fi
    done
    IFS=$oldifs
}

walk_tree "$1" "\.sh$"


#! /usr/bin/env bash
  
walk_tree() {
	ls "$1" | while IFS= read i; do
		if [ -d "$1/$i" ]; then
			echo "$i/"
			walk_tree "$1/$i" "$2" | sed -r 's/^/\t/'
		else
			echo "$i" | grep -E "$2"
		fi
	done
}
 
walk_tree "$1" "\.sh$"


  

You may also check:How to resolve the algorithm Arithmetic numbers step by step in the Arturo programming language
You may also check:How to resolve the algorithm Long literals, with continuations step by step in the Perl programming language
You may also check:How to resolve the algorithm Nonoblock step by step in the Elixir programming language
You may also check:How to resolve the algorithm Substring/Top and tail step by step in the Go programming language
You may also check:How to resolve the algorithm Unprimeable numbers step by step in the Python programming language