1

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.]
  • 1
    Use echo -n or printf. – DisplayName Jan 2 at 19:35
  • I should have looked at man echo in the first place. Thanks a lot! – KKor Jan 2 at 19:38
  • 3
    @KKor don't rely on man echo - your shell may have a builtin echo command that behaves differently. See for example Why is printf better than echo? – steeldriver Jan 2 at 19:47
1

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).

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
0
for i in `seq 1 10`; do
  printf "a " >> file
done

should do the trick.

  • 1
    or for ... do ... done >> file to avoid reopening file multiple times – Jeff Schaller Jan 2 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.