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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With