I want to append multiple files named lab_X.txt to one single output file final.txt. Knowing that all the files in one folder are the ones that I need I moved them into the current directory and used cat *.txt > final.txt
, knowing that >
overwrites the file. I want to insert a simple message between the files similar to =============
, is that possible?

- 162
- 2
- 5
- 15
-
As a hint simplest is to have a for loop through all the files where you first `cat` lab_X file to final.txt, than you `echo ====` and redirect it's output to file.txt. There are of course many hackish ways to do it as the ones @stickybit mentioned. – dmadic May 05 '18 at 23:45
2 Answers
Assuming you have Gnu awk:
awk 'BEGINFILE{print "============="}1' lab*.txt > final.txt
The BEGINFILE
special pattern (a gawk extension) triggers just before the first line of each file. It defines the variable FILENAME
in case you want to include the name in the separator line.
The 1
at the end is a pattern which is always true. Since it has no action, the default action is executed, which prints the line.
This will print the line at the beginning as well. If you really don't want that, you could add a check:
awk 'BEGINFILE{if(nfiles++)print "============="}1' lab*.txt > final.txt
There is nothing special about nfiles
. Like any other awk variable, it is effectively initialised to 0, and the postfix ++
increments it, but only after its value is returned.

- 234,347
- 28
- 237
- 341
With gnu sed
sed -ns '1s/.*/=============\n&/;w final.txt' lab*.txt
'-s' '--separate'
By default, 'sed' will consider the files specified on the command line as a single continuous long stream. This GNU 'sed' extension allows the user to consider them as separate files: range addresses (such as '/abc/,/def/') are not allowed to span several files, line numbers are relative to the start of each file, '$' refers to the last line of each file, and files invoked from the 'R' commands are rewound at the start of each file.

- 2,413
- 2
- 7
- 17