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 youRequired Output:
He llo
Wor ld
how are youMy Output:
He llo Wor ld how are you 0 2 Answers
:space: matches both horizontal and vertical white space. Use :blank: instead to match horizontal whitespace only.
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.txtWith 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.txtwith awk command:
awk '{$1=$1}1' < input.txt > output.txt
awk '$1=$1""' < input.txt > output.txt 0