BookmarkSubscribeRSS Feed
deleted_user
Not applicable
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.
4 REPLIES 4
sbb
Lapis Lazuli | Level 10 sbb
Lapis Lazuli | Level 10
Have a look at using the DATA step SCAN function.

Scott Barry
SBBWorks, Inc.
yonib
SAS Employee
You can do something like this:


data _null_;
w=compress('ABCDE_1234','_1234');
put w;
run;
Cynthia_sas
Diamond | Level 26
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]
deleted_user
Not applicable
Thank you Cynthia. It worked.

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 4737 views
  • 0 likes
  • 4 in conversation