Concatenate two files and separate them with a newline

I have two files:

k.txt:

3 5 7 9 19 20 

h.txt:

000010
100001
111001

if I just use cat, there is no newline. I need a command which would provide a file which looks like this:

3 5 7 9 19 20
000010
100001
111001
4

6 Answers

If, as steeldriver suggests, your files don't end with a newline, you could try:

awk '{print}' k.txt h.txt > newfile

or, if you like golfing

awk 1 k.txt h.txt > newfile

or

perl -lne 'print' k.txt h.txt 

or

( cat k.txt ; echo ""; cat h.txt; echo ) > newfile

or

echo "$(cat k.txt)"; echo "$(cat h.txt)"
7

Try this with bash:

cat k.txt <(echo) h.txt > new.txt
4

Using sed:

sed '/^/ r h.txt' k.txt

or better (thx @steeldriver)

sed '$a\' k.txt h.txt

Using ed:

(echo "0a"; cat k.txt; echo "."; echo "wq") | ed -s h.txt

and for the missing newline in k.txt:

(echo "0a"; cat k.txt; echo ""; echo "."; echo "wq") | ed -s h.txt

or if you need a separate output file:

(echo "0a"; cat k.txt; echo ""; echo "."; echo "w out.txt"; echo "q") | ed -s h.txt
3

Realizing that the file1 might not contain the newline, why not simply add the newline by yourself ? (cat file1.txt; printf "\n"; cat file2.txt ) > out.txt. Alternative way to do this, would be printf "\n" | cat file1.txt - file2.txt

1

That's the job for paste:

paste -sd'\n' file1 file2
  • -s make paste concatenate all of the lines of each file in command line order.
  • -d'\n' make paste used newline as delimiter.
1

Nobody has mentioned python yet. Here it is:

#!/usr/bin/env python2
with open('k.txt') as fk, open('h.txt') as fh, open('out.txt', 'a') as fo: for line in fk: fo.write(line) fo.write('\n') for line in fh: fo.write(line)

Here after reading the f.txt file we have inserted a newline manually in the out.txt file (fo.write('\n')) and then again append the content the k.txt file to the out.txt file. Finally out.txt will contain the desired output.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like