Date: Wed, 6 Mar 2002 12:56:54 +1200
Reply-To: Don_Stanley@BNZ.CO.NZ
Sender: "SAS(r) Discussion" <SAS-L@LISTSERV.UGA.EDU>
From: Don_Stanley@BNZ.CO.NZ
Subject: Replacing a string in a file
Content-type: text/plain; charset=us-ascii
I'm not sure from the digest thread who started this question, but heres the
solution that I use frequently if I have to do this in SAS-- and this works in
both V6 and V8 on both MVS and PC (although their are better ways in V8 as you
directly reference _infile_ in functions). Only caveat on this is that as
written below, the original and replacement strings need to be the same length.
gets more complex if you need to change the length.
Sample BEFORE file
0hgd 137
1jh jh jkh jk 1353 treyrt
1012345678901234567895hj d 137 klr hjklfj
1jkfhkrjghjfhgjf137ghfj137gkfh136gjfghfjghfjg kfjgkfgjkghfjg
9vljfflhkg
We want to change all "137" to "???"
Use code
data _null_ ;
/* in following INFILE statement */
/* set lrecl to be greater than the actual file width for variable width files
*/
/* use PAD to ensure that when a match is found in the last 3 columns, the
column
versus length check (c=len) can distinguish from a non-match. This is
because on a
non-match, the column pointer returns the same value as a match at the
record end,
hence the reason for making the lrecl longer and padding */
/* use truncover or weird things happen with input @'char string' */
infile 'c:\before_change.txt' column=c truncover length=len pad lrecl=64;
input @'137' @; /* read the record and scan for the string to be replaced */
file 'c:\new_file.txt' ;
put _infile_ @ ; /* write the record back out and hold the output pointer on
the line */
if c>len then do ; /* column pointer exceeds line length so no match */
put ; /* complete writing the record */
return ; /* finished with this record */
end ;
else
do until (c > len); /* loop through to ensure we get all occurrences of the
string */
put @(c-3) '???' @; /* at the string position write the replacement string
*/
input @c @'137' @ ; /* check for next occurrence of the string. If non,
then the */
/* column pointer will be set to the string length+1
*/
end ;
put ; /* complete when we had a match */
run ;
Resulting in AFTER file
0hgd ???
1jh jh jkh jk 1353 treyrt
1012345678901234567895hj d ??? klr hjklfj
1jkfhkrjghjfhgjf???ghfj???gkfh136gjfghfjghfjg kfjgkfgjkghfjg
9vljfflhkg
Don
WARNING: The contents of this E-mail may contain information that is legally
privileged and/or confidential to the named recipient. This information
is not to be used by any other person and/or organisation. The views
expressed in this document do not necessarily reflect those of the Bank
of New Zealand.