How to replace spaces and slash in string in bash?

harrison4 picture harrison4 · Mar 1, 2014 · Viewed 8.4k times · Source

Giving the string:

foo='Hello     \    
World! \  
x

we are friends

here we are'

Supose there are also tab characters mixed with spaces after or before the \ character. I want to replace the spaces, tabs and the slash by only a space. I tried with:

echo "$foo" | tr "[\s\t]\\\[\s\t]\n\[\s\t]" " " | tr -s " "

Returns:

Hello World! x we are friend here we are 

And the result I need is:

Hello World! x

we are friends

here we are

Some idea, tip or trick to do it? Could I get the result I want in only a command?

Answer

Gerrit Brouwer picture Gerrit Brouwer · Mar 6, 2014

The following one-liner gives the desired result:

echo "$foo" | tr '\n' '\r' | sed 's,\s*\\\s*, ,g' | tr '\r' '\n'
Hello World!

we are friends

here we are

Explanation:

tr '\n' '\r' removes newlines from the input to avoid special sed behavior for newlines.

sed 's,\s*\\\s*, ,g' converts whitespaces with an embedded \ into one space.

tr '\r' '\n' puts back the unchanged newlines.