How to gather the name of the files in each subdirectory into a text file in that subdirectory? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to gather the name of the files in each subdirectory into a text file in that subdirectory? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I wanted to save the names of all files in each sub directory into a text file in that sub directory, so I wrote this script:

#!/bin/bash
for X in "$PWD" *
do  
    if [ -d "$X" ];
    then
        cd "$X"
        files="$(ls)"
        echo "$files" >> filesNames.txt
    fi
done

but, I cannot enter sub directories using:

cd "$X"

What is wrong here?

Answer

Per your comments, you only have to descend one level deep. In that case you could use a glob to iterate over directories names and for each dir save file paths in an array, then print the last element of each path to fileNames.txt:

#!/bin/sh

for dir in "$PWD"/*/; do
arr=( "$dir"* )
printf %s\n "${arr[@]##*/}" > "$dir"filesNames.txt
done

To exclude symlinks just add a condition e.g. if [[ ! -L "${dir%?}" ]]; then arr...

We are here to answer your question about How to gather the name of the files in each subdirectory into a text file in that subdirectory? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji