Take the 2-minute tour ×

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

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 ?

share|improve this question
add comment

5 Answers

up vote 4 down vote accepted

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
share|improve this answer
sponge is a useful utility for overwriting an input file. It is part of package moreutils ... eg. awk '$1=$1' ORS=' ' file |sponge file –  Peter.O Dec 14 '11 at 6:17
@ferer Thanks for the information. Installing moreutils... –  pferor Dec 14 '11 at 13:25
add comment

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

a    test"

printf "$string" | xargs   # this is a test
share|improve this answer
add comment

If you already have the string as a bash variable, as your example shows, it is pointless and wasteful of resources (and more typing) to call sed, awk, printf, etc... You can just use bash variable expansion:

string="${string//$'\n'/ }"

You don't even have to re-assign it. You can use the expansion as-is, and leave $string unchanged.

printf "${string//$'\n'/ }" >file
share|improve this answer
add comment

You could try using tr instead:

share|improve this answer
add comment

Echo ignores white space, so it should work:

new_string=`echo $string`
share|improve this answer
Yes, it will work, but perhaps too well. It will collapse multi whitespace to a single space. That includes converting TABs to spaces. –  Peter.O Dec 14 '11 at 6:10
add comment

Your Answer


