I have multiple files which I want to concat with cat
.
Let's say
File1.txt
foo
File2.txt
bar
File3.txt
qux
I want to concat so that the final file looks like:
foo
bar
qux
Instead of this with usual cat File*.txt > finalfile.txt
foo
bar
qux
What's the right way to do it?
You can do:
Make sure the file
finalfile.txt
does not exist before you run the above command.If you are allowed to use
awk
you can do:If it were me doing it I'd use sed:
In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.
If your version of sed doesn't have
-s
(process input files separately) you can do it all as a loop though:That's how I just did it on OsX 10.10.3
since the simple 'echo' command with no params ended up in no new lines inserted.
In python, this concatenates with blank lines between files (the
,
suppresses adding an extra trailing blank line):Here is the ugly python one-liner that can be called from the shell and prints the output to a file:
If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:
You may do it using
xargs
if you like, but the main idea is still the same: