Operating System - HP-UX
1753785 Members
7541 Online
108799 Solutions
New Discussion юеВ

Re: how to get rid of trailing white spaces using awk

 
Kent Ostby
Honored Contributor

Re: how to get rid of trailing white spaces using awk

Fernando -- I'm making the assumption that you only want to get rid of white space at the end of the line.

sample data input (add three spaces after last word):

Fernando Fulgar Fernando

To test:
wc indata
1 3 30
{NOTE: one character is a carriage return)

Create a file, tw.awk, with this script in it:

{dalen=length($0);daflag=0;
for (idx1=dalen;daflag==0;idx1--)
{ if (substr($0,idx1,1)!=" ")
{print substr($0,1,idx1);exit}
}
}

awk -f tw.awk < indata > outdata

wc -l outdata
1 3 27 outdata

best regards,

Kent M. Ostby


"Well, actually, she is a rocket scientist" -- Steve Martin in "Roxanne"
Hein van den Heuvel
Honored Contributor

Re: how to get rid of trailing white spaces using awk

I like perl a lot, but in this case there is a perfectly reasonable, compact, readable awkward solution as requested.

As I replied earlier, but I guess is got overlooked, just use the SUBstitute function using "any number of spaces at end of variable" as ere (extended regular expression) and nothing ("") as replacement string on the variable of choice.
This case $2, and often you can just work on $0.

Solution:

sub(/ *$/,"",$2)


Cheers,
Hein.

Re: how to get rid of trailing white spaces using awk

If possible, i would rather use sed to get rid of heading and trailing spaces:

sed -e "s/^[ \t]*//; s/[ \t]*$//;"

Regards,
Alex
Pando
Regular Advisor

Re: how to get rid of trailing white spaces using awk

dear all,

it was a great help!
many thanks!