2

I want to replace multiple spaces by a single space. I am using tr to do this. But it is also replacing new line with a space. How can I avoid it?

Code:

tr -s [:space:] ' '

Input:

He  llo
Wor  ld
how  are  you

Required Output:

He llo
Wor ld
how are you

My Output:

He llo Wor ld how are you
0

2 Answers 2

11

:space: matches both horizontal and vertical white space. Use :blank: instead to match horizontal whitespace only.

2

Just use tr -s [:space:] without ' ' at the end to squeeze the consecutive whitespaces into one.

or you can use one of these commands:

With tr command:

tr -s ' '         < input.txt > output.txt
tr -s '[:blank:]' < input.txt > output.txt
tr -s \           < input.txt > output.txt

With sed command:

sed 's/  */ /g'             < input.txt > output.txt
sed 's/ \{1,\}/ /g'         < input.txt > output.txt
sed -E 's/ +/ /g'           < input.txt > output.txt
sed -E 's/[[:space:]]+/ /g' < input.txt > output.txt

with awk command:

awk '{$1=$1}1' < input.txt > output.txt
awk '$1=$1""'  < input.txt > output.txt
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .