John Threepwood
John Threepwood

Reputation: 16143

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

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

Upvotes: 25

Views: 66654

Answers (2)

xiphos71
xiphos71

Reputation: 31

An alternate way to echo results to one line would be to simply assign the results to variables. Example:

j=$(echo foo)
i=$(echo bar)
echo $j$i
foobar
echo $i $j
bar foo

This is particularly useful when you have more complex functions, maybe a complex 'awk' statement to pull out a particular cell in a row, then pair it with another set.

Upvotes: 3

cnicutar
cnicutar

Reputation: 182674

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

Upvotes: 57

Related Questions