tcople tcople - 1 month ago 6
Linux Question

Create .txt of all files in each subdirectory

I need to create a text file in each subdirectory of all files in the list.

For example, subdirectory1 would contain a list of all of its files as a .txt and subdirectory2 would also contain a list of all of subdirectory2 files as a .txt
I have tried

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


however this did not generate anything. I absolutely need it as a shell script because it will be part of a pipeline script, but I cannot seem to get it to work.

Here is the adjusted script giving me the no such file or directory comment. I know that the folder exists and have used it in commands that are run before this command.

#!/bin/bash

#Retrieve the base directory path
baseDir=$(dirname "$ini")

#Retrieve the reference genome path
ref=$(dirname "$genome")

#Create required directory structure
tested="$baseDir/tested"
MarkDups1="$baseDir/MarkDups1"

#don't create if already exists
[[ -d "tested" ]] || mkdir "$tested"
[[ -d "MarkDups1" ]] || mkdir "$MarkDups1"


#create a text file with all sorted and indexed bam files paths
#!/bin/bash
for x in $MarkDups1/*/;
do
(cd "$x"; ls > filesNames.txt)
done

Answer

The sequence to iterate over should be "$directory"/*/.

for x in "$directory"/*/; do
  (cd "$x"
   files=(*)
   printf '%s\n' "${files[@]}" > filesNames.txt
  )
done