4

Can I remove a newline if I redirect output like this?

echo "a" >> file

I have something similar in my script which contains a for loop that redirects every character (except numbers) to a file. But my goal is to have this output in one line. Let's say I redirect the "a" ten times so it should look like this:

a a a a a a a a a a

but it looks like this:

a
a
a
a 
[etc.]
DopeGhoti
  • 76,081
KKor
  • 55

3 Answers3

4

If you're specifically asking about echo, you can use -n to suppress the newline:

$ echo -n "test" >> outputfile

If you're asking more generally how to suppress newlines in piped or redirected data, this is a cat with many skins. One easy way is with tr:

$ do_stuff | tr -d "\n" >> outputfile

If you're just getting started with scripting and outputting data, it might be best to get out of the habit of using echo altogether in favor of printf:

$ printf "test" >> outputfile

printf is superior to echo in many ways and for many reasons, not least of which is that it only prints what you explicitly tell it to (and, arguably more importantly, in the format in which you want it).

DopeGhoti
  • 76,081
1

I don't think you'd want to delete the newlines, but replace them with spaces:

for ((i=0; i<10; ++i)); do
    echo a
done | tr '\n' ' ' >file

This simply post-processes your echo output and saves the data into file (truncating it first, if it already exists).

Or do something more fancy (in bash),

for ((i=0; i<10; ++i)); do
    array+=( "a" )
done

printf '%s\n' "${array[*]}" >file

This has the advantage of terminating the line properly with a final newline, while all the elements of the array are delimited by space (the first character of $IFS).

Or, with /bin/sh:

i=0
set --
while [ "$i" -lt 10 ]; do
    set -- "$@" "a"
    i=$(( i + 1 ))
done

printf '%s\n' "$*" >file
Kusalananda
  • 333,661
0
for i in `seq 1 10`; do
  printf "a " >> file
done

should do the trick.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255