When I echo $something >> file.txt, a new line will be append to the file.
What if I want to append without a new line?
14 Answers
That's what echo -n is for .
printf is very flexible and more portable than echo. Like the C/Perl/etc implementations, if you do not terminate the format string with \n then no newline is printed:
printf "%s" "$something" >> file.txt If you are using command's output, you can use xargs in combination with echo
/sbin/ip route|awk '/default/ { print $3 }' | xargs echo -n >> /etc/hosts tr is another alternative.
If you're using echo as your input you can get away which tr -d '\n'.
This technique also works when piping in output from other commands (with only a single line of output). Moreover, if you don't know whether the files have UNIX or DOS line endings you can use tr -d '\n\r'.
Here are some tests showing that this works.
Newline included:
something='0123456789' ; echo ${something} | wc -c
11UNIX newline:
something='0123456789' ; echo ${something} | tr -d '\n\r' | wc -c
10DOS style:
something='0123456789' ; echo ${something} | unix2dos | tr -d '\n\r' | wc -c
10Tested with BSD tr and GNU tr.