I have multiple files .txt which contain names of people sorted alphabetically so for example in main directory I have directory a which contains one a.txt full with names which start with "a" like "Anna" "Andrew" etc. The same thing repeats in main directory I have directory b containing b.txt full with names etc. up until x,y,z. How can I extract the names and create a master.txt containing all people's names?


You can accomplish this by using the cat command and filename expansion. If all of these files are in the source directory /path/to/directory, and there are no other files in this directory, then the most succinct command would be the following:

cat /path/to/directory/*/*.txt > master.txt

This will create a file called master.txt in your current directory which contains the concatenated contents of all of the files in the source directory. NOTE: This will include any files in any of the subdirectories of the source directory.

If there are other files in the directory (or if you just want to be a little bit more precise) then you can use this command instead:

cat /path/to/directory/[a-z]/[a-z].txt > master.txt

This will only match the following files in the source directory:


If there are other files in the source directory, or if you have files of the similar to a/z.txt where the subdirectory name doesn't match the base-name of the file, and if you want to exclude those files, then you would have to use a more precise command to narrow down the list of matched files. In that case you could use brace-expansion and a for-loop:

for letter in {a..z}; do \
    cat "/path/to/directory/${letter}/${letter}.txt"; \
done >> master.txt

This will match exactly the files you've specified in your question and no other files.


Replace main_dir with the path to your main directory, save this in a script and run from the terminal as sh ./script-name.sh

for i in $( cd main_dir && ls ); do
    cat "main_dir/$i/$i.txt" >> "master.txt"
  • 1
    There's no reason to parse the output of ls in this situation, since globbing/filename-expansion will work just as well. Also, parsing the output of ls is considered bad practice in general. See Why you shouldn't parse the output of ls for more on that topic. – igal Nov 19 '17 at 4:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.