How can I trim white space from a variable in awk?

Suppose $2 is my variable. I have tried going from

awk -F\, '{print $2 ":"}'

to

awk -F\, '{print gsub(/[ \t]+$/, "", $2) ":"}'

But it goes from printing something to printing nothing at all.


Solution 1:

You're printing the result of the gsub, but gsub does an in-place modify of $2 instead of returning a modified copy. Call gsub, then print:

awk -F\, '{gsub(/[ \t]+$/, "", $2); print $2 ":"}'

Solution 2:

These functions come in handy to improve readability. They also return the trimmed result:

function ltrim(s) { sub(/^[ \t\r\n]+/, "", s); return s }
function rtrim(s) { sub(/[ \t\r\n]+$/, "", s); return s }
function trim(s) { return rtrim(ltrim(s)); }
BEGIN {
# whatever
}
{
# whatever
}
END {
# whatever
} 

Source: https://gist.github.com/andrewrcollins/1592991

Solution 3:

(I don't have enough points to comment on the previous answer directly.)

To trim whitespace at the end of $2 use:

awk -F\, '{gsub(/[ \t]+$/, "", $2); print $2 ":"}'

To trim whitespace at the beginning of $2 use:

awk -F\, '{gsub(/^[ \t]+/, "", $2); print $2 ":"}'

And for both end and beginning:

awk -F\, '{gsub(/^[ \t]+/, "", $2); gsub(/[ \t]+$/, "", $2); print $2 ":"}'

Solution 4:

A one liner for gawk:

gawk -F\, '{$2 = gensub(/^[ \t]*|[ \t]*$/,"","g",$2)}'

Solution 5:

ltrim and rtrim in Unix

awk 'BEGIN{FS=OFS="|"} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' filename.txt