Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 787
Hoa Avatar asked Apr 03 '12 00:04

Hoa


People also ask

How do you trim a space in a Unix variable?

${var/ /} removes the first space character. ${var// /} removes all space characters. There's no way to trim just leading and trailing whitespace with only this construct.

How do you cut in awk?

You can cut in awk using awk's function split . You can also filter records using a regex condition within awk, making grep and cut superfluous. This breaks down like: Set the output field separator to be a pipe between two spaces.


Video Answer


1 Answers

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 ":"}' 
like image 154
je4d Avatar answered Oct 07 '22 23:10

je4d