Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace spaces and slash in string in bash?

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?

like image 884
mllamazares Avatar asked Feb 28 '14 23:02

mllamazares


1 Answers

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.

like image 158
Gerrit Brouwer Avatar answered Oct 02 '22 08:10

Gerrit Brouwer