0

I am trying to traverse through the sub directories under current directory. There are certain files that i want to access and process inside each sub--directories. Can anyone help how can I access files inside sub directories?

"
for dir in /home/ayushi/perfios/fraud_stmt/*; 
do echo $dir;


done;
"

This above script will echo all the sub directories. but instead of echoing I want to go inside the directories and access files that are present inside it.

1
  • use ls instead of echo Commented Sep 18, 2018 at 9:11

2 Answers 2

1
find /home/ayushi/perfios/fraud_stmt/ -type f | while read fname; do
    : do something on $fname here
done

This will search for all files (i.e. not actual directories) from the specified directory downwards. Note that you should enclose "$fname" in double quotes, in case it contains spaces or other "odd" characters.

Sign up to request clarification or add additional context in comments.

2 Comments

for dir in /home/ayushi/perfios/fraud_stmt/*;do find /home/ayushi/perfios/fraud_stmt/ -type f | while read fname;do: do echo $fname ; done I have written like this , this throws error...Can you please elaborate
No, my script was the whole thing - you don't need the "for" loop at all, and only one "do" in the middle of the line. Just copy my code, and change ": do something on $fname here" to "echo $fname"
1

An example using a recursive function

process_file() {
    echo "$1"
}

rec_traverse() {
    local file_or_dir
    for file_or_dir in "$1"/*; do
        [[ -d $file_or_dir ]] && rec_traverse "$file_or_dir"
        [[ -f $file_or_dir ]] && process_file "$file_or_dir"
    done
}

rec_traverse /home/ayushi/perfios/fraud_stmt
  • process_file can be changed to do something on file.
  • "$1"/* may be changed to "$1"/* "$1"/.* to match hidden directories but in this case special hard linked directories . and .. must be filtered to avoid infinite loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.