Shell script: How to append contents of one file to another WITHOUT line break

dirknibleck
dirknibleck used Ask the Experts™
on
I am trying to append text from one file to another, with the hitch being that I need the text from the source file to begin at the end of the last line of the original file, not on the next line.

I am currently using:

cat source.txt >> origin.txt

Thoughts on how I can change this?

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2013
Top Expert 2013
Commented:
(awk -v OL=$(wc -l < origin.txt|tr -d " ") '{if (NR<OL) print $0; else printf $0}' origin.txt; cat source.txt) > concat.txt

mv concat.txt origin.txt # if you're satisfied with the result

wmp
Hi dirknibleck,

This seems to work:
    perl -i -0pe 's/\n$//' origin.txt
    cat source.txt >>origin.txt

Notes:
- 1st line above removes the last new-line char from origin.txt.
- If the file is too big to fit in memory, then my method would not be advisable (but may still work, since virtual memory could be used).
- If there is a chance that origin.txt could contain a null (ASCII 0) char, change the "-0pe" to "-0777 -pe" (less concise, but more flexible).
- If you want to backup the old version of origin.txt as part of this, you could change the "-i" to something like "-i.bak" (which would backup to origin.txt.bak).

Author

Commented:
Thanks, that's exactly what I needed.
Hi dirknibleck,

Did you try my Perl solution?
Did it work?
Why did you not like it?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial