Removing tabs from a string using either sed or awk and tcl regsub function

249 Views Asked by At

Say I have a string as name = xyz here after name there is a tab and after '=' there are random number of spaces.

I need an output as name=xyz

So how can I remove both tabs and random number of spaces from the above mentioned string using sed or awk and tcl regsub function. Help is highly appreciated. Thanks.

I tried

[regsub -all { +} $str ""]

This removes the random number of spaces from $str but tabs are still present.

6

There are 6 best solutions below

0
markalex On BEST ANSWER

Here is also solution using sed

myvar=$(sed -E 's/\s*=\s*/=/g' <<<$myvar)

or, to be more portable you can use [[:space:]] instead of \s

myvar=$(sed -E 's/[[:space:]]*=[[:space:]]*/=/g' <<<$myvar)

Here every occurrence of = surrounded by any number of whitespace symbols will be replaces with just =, without any whitespaces.

5
tshiono On

\s matches both tab character and whitespace. Then would you please try:

[regsub -all {\s+} $str ""]

The potential problem here is it will remove blank characters anywhere regardless of the relevance to the = sign.

It will be safer to say:

[regsub {\t=\s*} $str "="]

which removes a tab character before = and whitespace(s) after =.

0
Daweo On

I would harness GNU AWK for this task following way

echo "name    = xyz" | awk 'BEGIN{OFS=""}{$1=$1;print}'

gives output

name=xyz

Explanation: GNU AWK assumes field separator is one-or-more whitespace character which is compliant with your use case, I set OFS to empty string so there will be nothing between fields, $1=$1 triggers string rebuild, print does print it. If you want to know more about OFS then read 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

(tested in GNU Awk 5.0.1)

0
markp-fuso On

Using bash parameter substitution:

$ str='name    = xyz'
$ str="${str//[ \t]/}"
$ echo "$str"
name=xyz

# or

$ str='name    = xyz'
$ str="${str//[[:space:]]/}"
$ echo "$str"
name=xyz
7
RARE Kpop Manifesto On

Another solution with awk:

echo 'name    = xyz' | awk NF++ OFS=

Results in

name=xyz
0
mrcalvin On

This question has received much of an attention, surprisingly. So, I throw in my take on the task. In Tcl, rather than using regsub, you may use the internal list parser to throw away the separating characters:

join [list {*}$str] ""

This certainly depends on whether you fully control the input string. It needs to conform to a valid string representation of a Tcl list.