Help using Base SAS procedures

To truncate a string after the "_" (Underscore).

Reply
N/A
Posts: 0

To truncate a string after the "_" (Underscore).

I have to truncate a string after the "_" (including underscore)

For example S1= ABCDE_1234
I would like to set S1=ABCDE.

How to I do this.
Super Contributor
Super Contributor
Posts: 3,174

Re: To truncate a string after the "_" (Underscore).

Posted in reply to deleted_user
Have a look at using the DATA step SCAN function.

Scott Barry
SBBWorks, Inc.
SAS Employee
Posts: 105

Re: To truncate a string after the "_" (Underscore).

Posted in reply to deleted_user
You can do something like this:


data _null_;
w=compress('ABCDE_1234','_1234');
put w;
run;
SAS Super FREQ
Posts: 8,868

Re: To truncate a string after the "_" (Underscore).

Hi:
The compress function will only work as long as the string is ALWAYS '_1234' at the end of the variable. Also, if any of the numbers or characters (_1234) is BEFORE the underscore, then those would also be compressed away. COMPRESS will get rid of ANY of the specified characters in the string, no matter where they are found -- before or after the underscore.

SCAN is probably the better function. Review the program and output below. METHOD1 variable was created with the SCAN function and METHOD2 was created with the COMPRESS function. Note the places where METHOD2 compressed in a way that might not be desirable.

Of course, the ultimate solution really depends on how the actual data looks.
cynthia

[pre]
data scan;
length s1 $12;
infile datalines;
input s1 $;
method1 = scan(s1,1,'_');
method2 = compress(s1,'_1234');
return;
datalines;
ABCDE_1234
XXXXX_1286
ABCDE_2222
A2CDE_7890
ZZZZZ_1234
;
run;

options nodate nonumber nocenter;
proc print data=scan;
run;
[/pre]

The output;
[pre]

Obs s1 method1 method2

1 ABCDE_1234 ABCDE ABCDE
2 XXXXX_1286 XXXXX XXXXX86
3 ABCDE_2222 ABCDE ABCDE
4 A2CDE_7890 A2CDE ACDE7890
5 ZZZZZ_1234 ZZZZZ ZZZZZ

[/pre]
N/A
Posts: 0

Re: To truncate a string after the "_" (Underscore).

Posted in reply to deleted_user
Thank you Cynthia. It worked.
Ask a Question
Discussion stats
  • 4 replies
  • 268 views
  • 0 likes
  • 4 in conversation