How to Replace Characters in a String in SAS (With Examples)

SAS provides a function called TRANWRD which is used to replace characters in a string. This function takes two arguments, the first being the string to be changed and the second being the characters to be replaced. Examples of how to use this function are provided, such as how to replace multiple characters in a string, how to replace the first and last character of a string, and how to replace characters with another string.


You can use the tranwrd() function to replace characters in a string in SAS.

Here are the two most common ways to use this function:

Method 1: Replace Characters in String with New Characters

data new_data;
    set original_data;
    new_variable = tranwrd(old_variable, "OldString", "NewString");
run;

Method 2: Replace Characters in String with Blanks

data new_data;
    set original_data;
    new_variable = tranwrd(old_variable, "OldString", "");
run;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data original_data;
    input team $1-20;
    datalines;
Angry Bees
Angry Hornets
Wild Mustangs
Kind Panthers
Kind Cobras
Wild Cheetahs
Wild Aardvarks
;
run;

/*view dataset*/
proc print data=original_data;

Example 1: Replace Characters in String with New Characters

The following code shows how to replace the word “Wild” in the team variable with the word “Fast”:

/*replace "Wild" with "Fast" in team variable*/
data new_data;
    set original_data;
    new_team = tranwrd(team, "Wild", "Fast");
run;

/*view new dataset*/
proc print data=new_data;

Notice that each team that had “Wild” in the name now has the word “Fast” in the name instead.

Any team that did not have “Wild” in the name simply kept their original name.

Example 2: Replace Characters in String with Blanks

The following code shows how to replace the word “Wild” in the team variable with a blank:

/*replace "Wild" with a blank in team variable*/
data new_data;
    set original_data;
    new_team = tranwrd(team, "Wild", "");
run;

/*view new dataset*/
proc print data=new_data;

Notice that any team that had “Wild” in the name simply had the word “Wild” replaced with a blank.

The following tutorials explain how to perform other common tasks in SAS:

x