Removing white space in awk

Hi

How to remove white space from this input:

|blue |   1|
|green|   4|
|black|   2|

I like to search for green and get

4

not

   4

How to modify this to work correct:

awk -F"|" '/green/ {print $3}

Try this:

awk -F"|" '/green/ {print $3/1}
2 Likes

Nice, never seen before. Where is this documented?

Thanks, this shows the power of awk :slight_smile:
Works fine as long as its number.

It's a forced type casting that I occasionally use in spread sheets to force a numeric value. I don't think it is documented anywhere. I just gave it a try in awk and it works.

1 Like

You can do also like this..

awk -F "|" '{gsub("^[ \t]*","",$3);print $3}' file

and ripat's code can be written also as (for numeric values)

$3+0 , $3*1 .

building on pamu's awk suggestion:

awk -F "|" '/green/ {sub("^[ \t]*","",$3);sub("[ \t]*$","",$3);print $3}' infile

Yes, it works, but keep in mind that division is far more cpu intensive than addition like $3+0 (as pamu suggests). No problem here, just remember every now and then.

---------- Post updated at 04:21 PM ---------- Previous update was at 04:17 PM ----------

If your awk allows for versatile field separators, try

$ awk -F"[| ]+" '/green/ {print $3}' file
4
1 Like