user1858409
user1858409

Reputation: 35

How do i write a bash script to loop through each directory in a folder and append all .txt files into a single file?

IN BASH: I have a directory containing a bunch of folders that each contain a .txt file I'd like to loop through each folder in the directory and concatenated all of the text files into one file. When I try the code I wrote below, I see bash is looping through each folder but nothing is added to the mergedfile:

for f in *; do
    if [ -d ${f} ]; then
        cd ${f}
        cat -name "*.txt" > mergedfile
        echo $f
        cd ..
    fi
done

I also noticed this error after each loop:

cat: illegal option -- a
usage: cat [-benstuv] [file ...]

Upvotes: 2

Views: 877

Answers (2)

techno
techno

Reputation: 535

Basically

For only 1 level of directory, this will do the job:

cat */*.txt >mergedfile

using globstar

For any level (0 or more) of subdirectories, you could use globstar bash option:

shopt -s globstar
cat **/*.txt >mergedfile

Upvotes: 0

Jay Shankar Gupta
Jay Shankar Gupta

Reputation: 6088

This appends the output to all.txt

cat *.txt >> all.txt

This overwrites all.txt

cat *.txt > all.txt

Correction in your code:

v="$PWD/mergedfile"    
for f in *; do
        if [ -d ${f} ]; then
            cd ${f}
            cat *.txt >> ${v}
            echo $f
            cd ..
        fi
    done

Upvotes: 1

Related Questions