May 5, 2011

f Comment

How Do You Insert Newlines With Unix 'cat' Command Correctly?

Amazon In Unix how do you use 'cat' command to combine multiple files into one with a newline (or any other character) inserted between each pair of files?

What I am trying to do is simple: I have multiple files and I'd like to run a Unix command to combine them into one big file, with newlines or breaks inserted following the content of each file. This is useful to for example combine many css files into one so that your website can reference only one css file but you can use many css files during development for easier understanding and modularization purposes.

It turns out that it's not so simple. You CANNOT use newline operators like \n in the shell command because it'll be interpreted incorrectly by the shell.
After some trial and error I finally arrived at the following solution.

1. Create a file called 'separator.txt' that contains one newline. If you use 'vi' program simply type 'i', 'Enter', 'ESC' or 'Escape', then 'ZZ'. If you want to insert other characters such as 'XXX' simply put 'XXX' in that file.

2. Use the 'cat' Unix command in the following manner, assuming you have three files you'd like to combine, fileA, fileB, fileC:

cat fileA separator.txt fileB separator.txt fileC > all.txt
Now open all.txt and it should contain the content of fileA, fileB, fileC with a newline (or whatever characters you put in the file 'separator.txt') inserted between each of them. If you'd like to insert 2 breaks between each two files simply add 2 newlines in the file 'separator.txt'.

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael