1

I'm trying to use gsub with awk to apply on all strings but failed.

gsub(/^ *| *$/,"", $4);

instead of applying this for string $4, i would like to apply it with all strings. i tried with $0 but failed.

What's wrong?

awk '{ 
     split($12, a, /[/:]/); 
     if (length(a[2]) == 1) $12=sprintf("%s:%02d/%d", a[1], a[2], a[3]);
     gsub(/^ *| *$/,"", $0);
     print $9, $12, $10, $2, $3, $4, $5, $6, $7, $8, $13 
 }' FS='|' OFS=',' file

EXAMPLE

|f_name:x|l_name:x| address:x x | city:x |state:x|zip:x|country:x|ordernumber:x|code:x|downloaded:x| exp:9/2017|ip:x.x.x.x|

Output

ordernumber:x,exp:09/2017,code:x,f_name:x,l_name:x,address:x x,city:x,state:x,zip:x,country:x,ip:x.x.x.x
3
  • you can iterate over all fields applying that gsub call. For relatively simple input strings I would also try sed substitution Dec 20, 2017 at 17:39
  • @RomanPerekhrest got it so it's can't applied to all without iterate ? Dec 20, 2017 at 17:42
  • 1
    @Sundeep done :) Dec 21, 2017 at 13:11

2 Answers 2

1

Loop from 1 to NF and refer to the field with $i (or whatever you use to name the loop counter). The syntax is similar to C:

for (i = 1 ; i <= NF ; i++) {
    ...
}

E.g.

$ echo "  foo bar  :doh : bla:" |awk -vOFS=: -F: '
    { for (i = 1 ; i <= NF ; i++) gsub(/^ +| +$/, "", $i) } 1'
foo bar:doh:bla:

(I changed /^ */ to /^ +/ as mawk seems to ignore the ^ in the former.)

2
1

If all you are trying to do is remove whitespace from each field, where the fields are separated by the character "|", then simply change the field delimeter to include that whitespace. Assuming your awk supports a regexp as field separator, replace your FS='|' setting with

FS=' *\\| *'

Note the need to escape the | as the strings is now a pattern.

This does not handle whitespace at the start of the first field, and end of the last field. You can use sub(/^ */,"",$1) and sub(/ *$/,"",$NF) on these.

1
  • 1
    to implement this: echo " foo bar :doh : bla:" |awk -vOFS=: -F' *: *' '{gsub(/^ *| *$/,""); $1=$1; print}' -- the $1=$1 bit is required to rewrite the string to convert the input field separators to the output field separators. Dec 20, 2017 at 19:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .