Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append strings to the same line instead of creating a new line?

Tags:

Redirection to a file is very usefull to append a string as a new line to a file, like

echo "foo" >> file.txt echo "bar" >> file.txt 

Result:

foo bar 

But is it also possible to redirect a string to the same line in the file ?

Example:

echo "foo" <redirection-command-for-same-line> file.txt echo "bar" <redirection-command-for-same-line> file.txt 

Result:

foobar 
like image 653
John Threepwood Avatar asked Sep 06 '12 10:09

John Threepwood


People also ask

How do you append without a new line?

Assuming that the file does not already end in a newline and you simply want to append some more text without adding one, you can use the -n argument, e.g. However, some UNIX systems do not provide this option; if that is the case you can use printf , e.g. Do not print the trailing newline character.

How do I append a line in echo?

This appending task can be done by using 'echo' and 'tee' commands. Using '>>' with 'echo' command appends a line to a file. Another way is to use 'echo,' pipe(|), and 'tee' commands to add content to a file.


1 Answers

The newline is added by echo, not by the redirection. Just pass the -n switch to echo to suppress it:

echo -n "foo" >> file.txt echo -n "bar" >> file.txt 

-n do not output the trailing newline

like image 157
cnicutar Avatar answered Sep 28 '22 12:09

cnicutar