how do I echo $something >> file.txt without carriage return?

84

17

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?

onemach

Posted 2012-03-01T08:25:33.467

Reputation: 2 575

3Be careful doing echo $something, its behavior depends on the IFS variable, and you could end up with disappearing character. You can try the following: var="hello world"; echo $var (two spaces between hello and world) or var="hello world"; IFS='l'; echo $var or var="-e hello \\n world"; echo $var. To solve that, put double quotes around the variable like this: echo "$var", or use printf. – jfg956 – 2012-03-01T12:17:29.493

Answers

98

That's what echo -n is for .

Ignacio Vazquez-Abrams

Posted 2012-03-01T08:25:33.467

Reputation: 100 516

@cboettig , cat does not add anything to the output by default, so there is no need for a '-n' param for cat. eg, if your file does not have a line-ending in the last line, then your shell prompt will be printed right after the last character of the file and not in a new line – Rondo – 2017-07-18T22:53:09.920

4Is there an equivalent for cat? (e.g. when you have a file something.txt rather than a variable $something) – cboettig – 2013-11-19T23:05:42.350

1@cboettig: No. Use a different tool to print everything but the final newline. – Ignacio Vazquez-Abrams – 2013-11-19T23:09:03.933

42

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

glenn jackman

Posted 2012-03-01T08:25:33.467

Reputation: 18 546

7

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

zainengineer

Posted 2012-03-01T08:25:33.467

Reputation: 171

0

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
11

UNIX newline:

something='0123456789' ; echo ${something} | tr -d '\n\r' | wc -c
10

DOS style:

something='0123456789' ; echo ${something} | unix2dos | tr -d '\n\r' | wc -c
10

Tested with BSD tr and GNU tr.

Nic Doye

Posted 2012-03-01T08:25:33.467

Reputation: 1