Join text files with filenames

You can use cat to join the contents of files. For example, this will create a file called tmpfile that contains the contents of all .txt files in the current directory:

cat *.txt > tmpfile

Use >> to append to tmpfile rather than overwriting it.

To include the filename of each .txt file you have to use a little shell scripting:

for i in *.txt; do echo -e "\nFilename: $i\n"; cat "$i"; done > tmpfile; mv tmpfile all-files.txt;

That will merge the files, appending the filename (surrounded by line breaks and preceded by ‘Filename: ‘) before the contents of each file. It will create a temporary file called tmpfile before renaming it as all-files.txt, which is necessary to prevent ‘input file is output file’ warning from cat.

To deconstruct that a little, echo "$i will output the filename and cat "$i" will output the contents. The -e flag causes echo to interpret backslashes i.e. the line breaks in this case.

Example:

me@pc ~ $ echo "Testing testing 123" > test1.txt
me@pc ~ $ echo "Testing testing 234" > test2.txt
me@pc ~ $ for i in *.txt; do echo -e "\nFilename: $i\n"; cat "$i"; done > tmpfile; mv tmpfile all-files.txt;
me@pc ~ $ cat all-files.txt

Filename: test1.txt

Testing testing 123

Filename: test2.txt

Testing testing 234

References

Last modified: 03/08/2013 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top