SAS Functions

Find and Replace a String in SAS with TRANWRD

Suppose you want to find and replace a string in SAS. You can do this with the TRANWRD function. The text string can be a word, a phrase, or just a simple character. The syntax of the TRANWRD function is:

TRANWRD(input variable, target, replacement)

For example, you have a SAS data set with street names and you want to create a new variable where the word Street has been replaced by Avenue. You can use the following code:

TRANWRD(address, ‘Street’, ‘Avenue’)

Find and Replace in SAS with TRANWRD

As you can see in row 5, the word STREET is not replaced by Avenue because the TRANWRD function is case sensitive. The code that has been used to create this example is:

data work.ds;
	input address $1-20;
	datalines;
Lombard Street
Abbey Road
Fifth Avenue
Beale Street
DOWNING STREET
Bourbon Street
Kings Road
;
run;

data work.ds_tranwrd;
	set work.ds;
	
	address_tranwrd=tranwrd(address, 'Street', 'Avenue');
run;

However, if you don’t want to find and replace a string in SAS, but only want to check if a string contains a substring you can use the FIND function. Click here for the official SAS documentation of the TRANWRD function.

2 thoughts on “Find and Replace a String in SAS with TRANWRD

Comments are closed.