Robert Penridge
Robert Penridge

Reputation: 8513

Append to last line of file

In the below code, is there an easy way to append to the last line of the file without using the @ symbol? I want to do this all in a single data step.

data _null_;

  file "%sysfunc(pathname(work))\test.txt" lrecl=1000;

  do cnt=1 to 10;
    put cnt;
  end;

  put #10 "append to last line";   

run;

For some reason my code is advancing the line pointer by 10 lines instead of going to line 10. Am I misinterpreting the help doc ? And even if it did go to line 10, how would I move the column pointer to the end of the line?

Desired result:

1
2
3
4
5
6
7
8
9
10append to last line

Upvotes: 3

Views: 213

Answers (2)

Joe
Joe

Reputation: 63424

The # operator works relative to the current line. SAS writes files in a linear fashion, always moving forward never moving backwards, unless you tell it to hold the line pointer (with @ or @@). Note that if you don't have the @ in Dom's example, you don't get the desired behavior either: that's because he's keeping the line pointer on row one the whole time.

So you basically have two choices: always move forward, or hold the line pointer and tell SAS to write to various lines ahead of the held line pointer. You use @ or @@ to hold the line pointer (not across or across data step boundaries).

The only way to write to a line without @ is to write the bit before the ; on put, which you'd have to write code to do I suppose:

 data _null_;

  file "%sysfunc(pathname(work))\test.txt" lrecl=1000;

  do cnt=1 to 9;
    put cnt;
  end;
  put cnt +(-1) "append to last line";


run;

But that seems sort of like cheating.

Upvotes: 3

DomPazz
DomPazz

Reputation: 12465

Only way I can get the output from the toy problem is to use the @ symbol. I suppose this is not an answer:

data _null_;

  file "%sysfunc(pathname(work))\test.txt" lrecl=1000;

  do cnt=1 to 10;
    put #(cnt) cnt @;
  end;

  put +(-1) "append to last line";   

run;

In this case, the # functions as expected, moving the output to the desired line with @ holding the pointer there after writing. Subsequent put statements can then append to that line.

Why it doesn't work in your problem example is beyond me.

Without this method, I don't think there is an easy way to append to a line without keeping track of the length of each line. You could build a hash table for each line and store the length as you print it. That would let you know what column you would need to start writing to later.

Upvotes: 3

Related Questions