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
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)"
$(cat file)
will strip any trailing newlines, and echo
will explicitly add one. FYI, bash has a builtin for $(cat file)
==> $(<file)
-- save a few microseconds. And with one command: printf "%s\n" "$(<k.txt)" "$(<h.txt)"
Jun 23, 2015 at 18:48
Try this with bash:
cat k.txt <(echo) h.txt > new.txt
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
sed '$a\' k.txt h.txt
Jun 23, 2015 at 18:11
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.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
printf "\n" | cat file1.txt - file2.txt
would be more idiomatic (and spares the life of one poor cat)
Jun 23, 2015 at 18:07
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.
cat
?cat k.txt h.txt > newfile
will create exactly the output you show.ms
(doco).