1

When I enter the following:

echo "This   is   for    testing" | tr -s [:space:]

I get this:

This   is   for    testing

I was hoping to remove the multiple spaces and just have one space between the words. I don't see what I am doing wrong.

karel
  • 122,695
  • 134
  • 305
  • 337
daveh
  • 91
  • It worked for me. I copied and pasted your exact text into an SSH session on my test 20.04.4 Ubuntu server. – Doug Smythies Sep 07 '22 at 00:08
  • 1
    Is there a file in the current directory with single-character name :, s, p, a, c or e? Does it work with tr -s '[:space:]'? – steeldriver Sep 07 '22 at 00:17
  • I tried it. It didnt work. Then I piped it to hexdump. It looks like the chars arent really spaces. Maybe if you copied the command from a web page, they arent spaces. But, I tryed typing it out and it workd as expected – petep Sep 07 '22 at 00:24
  • Omg I never thought to check, they weren't spaces. Thanks for the insight. – daveh Sep 08 '22 at 04:13

2 Answers2

2

In tr -s [:space:], the unquoted [:space:] will be treated by the shell as a glob, and if you a file that matches that glob (a filename with a single character of any of :, a, c, e, p, s), then your shell (likely bash) will expand that glob to that filename:

bash-5.1$ echo tr -s [:space:]
tr -s [:space:]
bash-5.1$ touch c
bash-5.1$ echo tr -s [:space:]
tr -s c

(It might also do other things based on shell options.)

So, use quoting so that the shell doesn't interpret [:space:]:

echo "This   is   for    testing" | tr -s '[:space:]'
muru
  • 207,970
1

It works for me in squeezing the spaces, maybe it doesn't work for you because those spaces in your sample text aren't really spaces,

They could be tabs

Try this

echo "This   is   for   testing" | tr \\t " "

or, if there are multiple tabs you can try using

echo "This  is   for   testing" | tr \\t " " | tr -s [:space:]
visdev
  • 36
  • 4