How do I get `tr` command to ignore newline?

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

: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.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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like