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
8

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

1

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

  • 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 '14 at 12:28
  • @muru correct. I have edited my answer. – αғsнιη Aug 30 '14 at 12:36
  • @KasiyA you should give 1st preference to tr as questioned for it. so reorder. – Pandya Aug 31 '14 at 6:18

Your Answer

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

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