triple fault
triple fault

Reputation: 14098

Removing whitespaces from a string

Suppose I have a string like this:

string="   this    is a string     "

What is the simplest way to remove duplicated whitespaces and get the following string:

string="this is a string"

Upvotes: 0

Views: 127

Answers (5)

iruvar
iruvar

Reputation: 23374

Make the shell's word-splitting work for you (assuming a default value for IFS).

string="   this    is a string     "
arr=($string)
printf -v string2 "%s" "${arr[*]}"
echo _${string2}_
_this is a string_

Upvotes: 0

svante
svante

Reputation: 1385

Solution using echo :

string=$(echo $string)

Upvotes: 1

konsolebox
konsolebox

Reputation: 75458

No need to use external binaries like Awk. You can do that in Bash alone.

string="   this    is a string     "
IFS=' ' read -a __ <<< "$string"; string="${__[@]}"
echo "$string"
this is a string

Another solution:

shopt -s extglob  ## need to be set only once.
string=${string##*([[:blank:]])}; string=${string%%*([[:blank:]])}; string=${string//+([[:blank:]])/ }

Or just specific to spaces ($'\x20')

string=${string##*( )}; string=${string%%*( )}; string=${string//+( )/ }

Upvotes: 2

Rohit Saxena
Rohit Saxena

Reputation: 56

Traverse the string character by character. Whenever you get two consecutive whitespaces, shift the array one character backwards

Upvotes: 0

Kent
Kent

Reputation: 195029

this line should work for the given example:

awk '$1=$1' <<< $string

see test:

kent$  x="   this    is a string     "

kent$  awk '$1=$1' <<< $x
this is a string

Upvotes: 3

Related Questions