I have been asked to get the matched keyword from a text file and get 2 lines/observations before and 2 lines/observations after.My data looks like this
data have;
input var$25.;
Description
This is a
format
for
the
variable
named
Default
it is changed
in release 5
change was
logged on 18 Jan 2015
;
run;
What I want in output is
variable |
named |
Default |
it is changed |
in release 5 |
Here , i tried using the Index function something like this
Data want;
set have;
if index(var,"default") >1 then output;
run;
But it is producing just 1 line, however i want 2 lines above and 2 lines below.
Please suggest some alternatives
Assuming that your "IF" condition properly selects the records you want:
data want;
set have nobs=_totalobs_;
if index(var, "default") then do _k_ = max(1, _n_-2) to min(_totalobs_, _n_+2);
set have point=_k_;
output;
end;
run;
You may need to adjust the IF condition to handle variations in spelling, such as uppercase vs. lowercase. Also, this outputs 5 lines: the line itself, as well as 2 before and 2 after. If you wanted to eliminate the line itself, that would be possible with minor changes:
if _n_ ne _k_ then output;
Good luck.
Good luck.
Assuming that your "IF" condition properly selects the records you want:
data want;
set have nobs=_totalobs_;
if index(var, "default") then do _k_ = max(1, _n_-2) to min(_totalobs_, _n_+2);
set have point=_k_;
output;
end;
run;
You may need to adjust the IF condition to handle variations in spelling, such as uppercase vs. lowercase. Also, this outputs 5 lines: the line itself, as well as 2 before and 2 after. If you wanted to eliminate the line itself, that would be possible with minor changes:
if _n_ ne _k_ then output;
Good luck.
Good luck.
Or construct an sequential index upfront:
data have;
input var $25.;
n=_n_;
cards;
Description
This is a
format
for
the
variable
named
Default
it is changed
in release 5
change was
logged on 18 Jan 2015
;
run;
proc sql;
create table want as
select b.var
from have (where=(find(var,'Default')>0)) a
left join have b
on b.n between a.n-2 and a.n+2
order by b.n;
quit;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.