Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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
share|improve this question

2 Answers 2

up vote 7 down vote accepted

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

share|improve this answer

You can use your own method:
just use single tr -s [:space:] without ' ' at the end

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 's/ \+ / /g'             < input.txt > output.txt
sed -e "s/[[:space:]]\+/ /g" < input.txt > output.txt


with awk command:

awk '{$0=tolower($0);$1=$1}1' < input.txt > output.txt
awk '$1=$1'                   < input.txt > output.txt
awk '{$1=$1}1' OFS=" "        < input.txt > output.txt


The output of each these commands is as tha sane as follows:

He llo
Wor ld
how are you


Note: your file is saved as name "input.txt" and output written into a new file named "output.txt".

share|improve this answer
    
IO redirection is any day better than cat. Especially in the case of sed. sed uses filenames in the arguments and reads from them. smallo.ruhr.de/award.html –  muru Aug 30 at 12:28
    
@muru correct. I have edited my answer. –  KasiyA Aug 30 at 12:36
    
@KasiyA you should give 1st preference to tr as questioned for it. so reorder. –  Pandya Aug 31 at 6:18
    
@Pandya I have edited. thanks –  KasiyA Aug 31 at 6:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.