Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing trailing spaces within delimited file 1

Status
Not open for further replies.

rufflocks

Technical User
Joined
Jun 29, 2001
Messages
26
Location
US
The file is comma delimited.
There are trailing spaces before the next comma.
eg: first name,last name ,address1 ,address2,

How do I remove these trailing spaces before the next comma
so that the output looks as follows?
eg: first name,last name,address1,address2,
 

function trim()
{
for (i=1; i <= NF; i++) {
nsub1=gsub(&quot;^[[:space:]]+|[[:space:]]+$&quot;, &quot;&quot;, $i);
printf(&quot;%s%s&quot;, $i, (i < NF-1) ? FS : &quot;&quot;);
}
printf(&quot;\n&quot;);
}
 
I was hoping for something simplier.
But while I wait, can I include that function within
an awk script that will be used to eventaully process the file?
 
I tried the function as a stand-alone.
The results were that 1 trailing space was left before the comma.
eg: first name,last name ,address1 ,address2,

produced:
first name,last name ,address1 ,address2,

instead of:
first name,last name,address1,address2,


 


ooops, sorry about that. Here's a better version

function trim()
{
for (i=1; i <= NF; i++) {
nsub1=gsub(&quot;^[ ]+|[ ]+$&quot;, &quot;&quot;, $i);
printf(&quot;%s%s&quot;, $i, (i < NF-1) ? FS : &quot;&quot;);
}
printf(&quot;\n&quot;);
}
 
I don't know if you find this is simpler, but it should do the job.
Code:
gsub(&quot; *, *&quot;,&quot;,&quot;)
Hope this helps. CaKiwi
 
Thanks.
The final script took the following form, and it works:

cat infile1 | nawk -F ',' '{gsub(&quot; *, *&quot;,&quot;,&quot;);print $0}' > filename
 
You could simplify it slightly by making the input file an argument to awk instead of using cat. Also, print prints the current line by default so the $0 is not necessary
Code:
nawk -F ',' '{gsub(&quot; *, *&quot;,&quot;,&quot;);print}' infile > filename
CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top