Question

I have a string in a variable and want to delete all whitespaces. I wish to do it with bash-only. Currently I remove only spaces, but I want to remove tabs also and in one step.

string="test    string 1" # first whitespace in string is tab second is space
echo ${string// /} # the whitespace between // is space; output: test   string1
echo ${string// /} # the whitespace between // is tab; output: teststring 1 

The wide whitespace are tabs. The third / could be removed.

@anubhava I read those strings line by line from a file, so there are no newlines in my string. Therefore it can't do any harm to remove all whitespaces.

Was it helpful?

Solution

Instead of attempting to replace a space, use a character class that would match any whitespace:

$ string=$'test\tstring 1'
$ echo "$string"
test    string 1
$ echo "${string//[[:space:]]/}"
teststring1

[:space:] denotes [ \t\r\n\v\f], i.e. it would match a space, tab character, carriage return, newline, and form feed.

As @glennjackman points out, you could remove the horizontal whitespace by using the character class [:blank:]:

echo "${string//[[:blank:]]/}"

If you want to remove only spaces and tabs, say:

echo "${string//[ $'\t']/}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top