Search code examples
sasspacestring-lengthtrailing

Prevent SAS to automatically remove trailing blank in string


I have a sample data set like below.

data d01;
   infile datalines dlm='#';
   input Name & $15. IdNumber & $4. Salary & $5. Site & $3.;
   datalines;
アイ# 2355# 21163# BR1
アイウエオ# 5889# 20976# BR1
カキクケ# 3878# 19571# BR2
;

data _null_ ;
 set d01 ;
 file "/folders/myfolders/test.csv" lrecl=1000 ;
 length filler $3;
 filler = '   ';
 w_out = ksubstr(Name, 1, 5) || IdNumber || Salary || Site || filler;
 put w_out;
run ;

I want to export this data set to csv (fixed-width format) and every line will has the length of 20 byte (20 1-byte-character).

enter image description here

But SAS auto remove my trailing spaces. So the result would be 17 byte for each line. (the filler is truncated)

I know I can insert the filler like this.

put w_out filler $3.;

But this won't work in case the `site' column is empty, SAS will truncate its column and the result also not be 20 byte for each line.


Solution

  • I didn't quite understand what you are trying to do with ksubstr, but if you want to add padding to get the total length to 20 characters, you may have to write some extra logic:

    data _null_ ;
     set d01 ;
     file "/folders/myfolders/test.csv" lrecl=1000 ;
     length filler $20;
     w_out = ksubstr(Name,1,5) || IdNumber || Salary || Site;
    
     len = 20 - klength(w_out) - 1;
     put w_out @;
     if len > 0 then do;
       filler = repeat(" ", len);
       put filler $varying20. len;
     end;
     else put;
    run ;