Find and Replace in SAS
Within SAS there are various ways of executing a find and replace within our data. One way that we can do this is to use the TRANWRD function. The TRANWRD function has three arguments. The first argument tells SAS which variable to look at, the second tells SAS the string to search for and the third is what you would like to replace the string with.
In this example we are going to look at the Tmine data set in the SASHELP library.
The Key variable in this table contains a two level name.
However we want to rename the EMTOOL library to New_Tool. This means that we would need to update any references to EMTOOL in the Key variable. To do this we can use the TRANWRD function.
data change_emtool; set sashelp.tmine; key=tranwrd(key,'EMTOOL','New_Tool'); run;
In this data step we are recreating the variable key with the result from the TRANWRD function. We are searching Key (the first argument) for the string 'EMTOOL' (the second argument) and replacing it with 'New_Tool' (the third argument).
The results are as follows:
Note that if we had used ‘emtool’ instead of ‘EMTOOL’ as the second argument, then the value would not have been changed as this is case sensitive . To overcome the case issue we could use the UPCASE function on the variable Key. There is also a TRANSLATE function that is similar to the TRANWRD function however it converts every occurrence of the specified character(s) to another character(s).