Shell – Using sed to convert newlines into spaces

sedshell

Say I have a shell variable $string that holds some text with several newlines, e.g.:

string="this
is 
a test"

I would like to convert this string into a new string new_string where all line breaks are converted into spaces:

new_string="this is a test"

I tried:

print $string | sed 's/\n/ /g'

but it didn't work

I'm also wondering if there is a way of doing this using perl -0777 's/\n/ /g' or maybe the command tr ?

Best Answer

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
Related Question