I've my inputs as below.
9161-642-524
9161-7642525
9167642526
642526
642
I need ouput as follows
09161
09161
91676
64252
00642
It means I need only 5 digits in output. If we've any speacial characters or the input record is less than 5 digits then we need to ignore those records and it should be produced with leading zeros.
I've tried this with substr and length function also with the format Z5. But it doesn't helped me either.
Hello,
Here you have one solution:
proc format;
picture frm
low-high='99999';
run;
data have (keep=varwant want) ;
length want 5 ;
input varwant $30.;
dashpos=index(varwant, "-");
if 1 <= dashpos <= 5 then want=substr(varwant,1,dashpos - 1);
else want=substr(varwant,1,5);
format want frm.;
datalines;
9161-642-524
9161-7642525
9167642526
642526
642
;
Below is totally over the top in case this is a once-off task. If it is something you need regularly then you might consider the approach.
It is based on Base SAS(R) 9.4 Procedures Guide, Third Edition
proc fcmp outlib=work.functions.smd;
function print_str(in_str $) $;
r=put(input(scan(in_str,1,,'kd'),5.),z5.);
return(r);
endsub;
run;
options cmplib=(work.functions);
proc format;
value $print_str (default=5) other=[print_str()];
run;
data have;
infile datalines truncover;
input mystring $10.;
datalines;
9161-642-524
9161-7642525
9167642526
642526
642
;
run;
proc print data=have;
format mystring $print_str.;
run;
Data A;
Input N $;
N5_Text=Put(Input(Substr(Scan(Compress(N),1,'-'),1,5),5.),Z5.);
N5_Num=Input(Substr(Scan(Compress(N),1,'-'),1,5),5.); Format N5_Num Z5.;
Datalines;
9161-642-524
9161-7642525
9167642526
642526
642
;
Run;
I believe you could simplify your nested functions as below:
N5_Text=put(input(scan(N,1,,'kd'),5.),z5.);
N5_Text=input(scan(N,1,,'kd'),5.);
data have; infile datalines truncover; input mystring $20.; datalines; 9161-642-524 9161-7642525 9167642526 642526 642 ; run; data want; set have; length temp $ 5; temp=mystring; want=input(compress(temp,,'kd'),best.); format want z5.; run;
Xia Keshan
Just to be "picky": What about a source string like "916-7642525"?
Not sure. Maybe I misunderstood OP's meaning . Let OP judge it anyway . Patrick.Matter !
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.