Using sed to convert newlines into spaces

If you only want to remove the new lines in the string, you don't need to use sed. You can use just

$  echo "$string" | tr '\n' ' '

as others had pointed.

But if you want to convert new lines into spaces on a file using sed, then you can use:

$ sed -i ':a;N;$!ba;s/\n/\t/g' file_with_line_breaks

or even awk:

$ awk '$1=$1' ORS=' ' file_with_line_breaks > new_file_with_spaces

You could try using tr instead:

echo "$string" | tr '\n' ' '

Yet another option would be to use xargs (which, in addition, squeezes multiple white space):

string="this
    is 
a    test"

printf "$string" | xargs   # this is a test

Tags:

Shell

Sed