Hi - does anyone know how to use the "X" command to modify a file? I would like to insert a line at the beginning and end of file. This would be in Unix/linux. Thanks
See here: https://unix.stackexchange.com/questions/20573/sed-insert-text-after-the-last-line
It also includes the sed comnand for inserting at the top.
You can do the same thing with pure SAS means:
date _null_;
infile "file_to_read";
file "newfile" end=done;
input;
if _n_ = 1 then put "text for top";
put _infile;
if done then put "text for bottom";
run;
and then use the SAS file functions in a follow-up step to remove the old file and rename the new.
Yeah I tried the SAS datastep approach, but for some reason it is truncating my input line even though I'm specifying LRECL = 32767. So I'm going with the Unix command and running that through the "x" command in SAS. As such, the following x command syntax works for me in SAS to insert at the END of the file:
x 'echo "text you want to insert" >> filepath/filename'
But when I try the following syntax to insert a line at the BEGINNING of the file, it doesn't seem to work, i.e., nothing happens?
x 'echo 'sed -i '1i "text you want to insert" >> filepath/filename'
Any tips appreciated. Much thanks!
The complete commandline for the sed call is this:
sed -i '1s/^/text you want to insert'\n' filepath/filename
So the SAS statements will be
x "sed -i '1s/^/text you want to insert on top'\n' filepath/filename";
x "echo 'text you want to insert at end' >> filepath/filename";
Please also post the data step code you tried.
Below is the data code I had tried. I am populating the filename with a macro variable set earlier (not shown). The file modification is working, just truncating certain lines for some reason.
filename output pipe "ls -a /mypath/*myfile*";
%macro create_xml;
%if &totalfiles gt 0 %then %do;
%do i=1 %to &totalfiles;
data _null_;
infile "&&filenm&i" lrecl=32767 end = last;
/* moddate=finfo(fid,'Last Modified');*/
do while(not last);
input;
file "&&fileout&i";
if lag("&&filenm&i") ne "&&filenm&i" then do;
put "mytext1"; /* beginning of file */
end;
put _infile_;
end;
if last then do;
put "</root>";
end;
run;
%end;
%end;
%mend create_xml;
Also, just to document what worked for me to insert the first line in file:
x "sed -i '1i mytext' /mypath/myfile.txt";
Your data step code is much too complicated. Use mine as a blueprint.
In particular, this
if lag("&&filenm&i") ne "&&filenm&i" then do;
makes no sense, as lag cannot work with strings, only data step variables. It seems you tried to adapt code that reads filenames from a dataset and reads multiple files, but you only need to read and write a single file in one step.
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.
Ready to level-up your skills? Choose your own adventure.