使用多个定界符和字符变量中的换行符从文本文件将数据导入SAS

时间:2018-12-11 17:17:12

标签: sas

我想将使用两个不同定界符“ |”的文本文件数据集读入SAS。和字符串“ [end text]”。安排如下:

var1|var2|var3
4657|366|text that 
has some line 
breaks [end text]
45|264| more text that has
line breaks [end text]

我试图弄清楚如何识别这两个定界符。我尝试使用DLMSTR选项,但这不起作用:

data new ;
  infile 'file.txt' dlmstr='|'||'[report_end]'  DSD firstobs=2 ;
  input var1 var2 var3 $;
run;

有什么办法可以同时使用这两个定界符?还是我使用了错误的输入样式来导入数据?

1 个答案:

答案 0 :(得分:1)

SAS可以读取带有嵌入式换行符的定界文件,只要嵌入式换行符使用与正常换行符不同的字符即可。因此,如果您的实际观察结果以CRLF(对于Windows文本文件而言正常)结尾并且嵌入的换行符只是单个LF字符,则这些多余的换行符将被视为该字段中的另一个字符。

var1|var2|var3<CR><LF>
4657|366|text that<LF> 
has some line<LF>
breaks [end text]<CR><LF>
45|264| more text that has<LF>
line breaks [end text]<CR><LF>

例如,这是一个数据步骤,可以转换您的原始文件。

data _null_;
  infile original lrecl=32767 ;
  file copy lrecl=1000000 termstr=lf ;
  input ;
  _infile_ = tranwrd(_infile_,'[end text]','0d'x);
  if _n_=1 then _infile_=trim(_infile_)||'0d'x;
  len = length(_infile_);
  put _infile_ $varying32767. len  ;
run;

但是最好将嵌入的换行符替换为其他字符,例如^。

data _null_;
  infile original truncover ;
  file copy lrecl=1000000 ;
  input line $char32767.;
  len = length(line);
  put line $varying32767. len @;
  if _n_=1 or index(_infile_,'[end text]') then put ;
  else put '^' @;
run;

结果:

var1|var2|var3
4657|366|text that^has some line^breaks [end text]
45|264| more text that has^line breaks [end text]

哪个很容易阅读。

Obs    var1    var2                      var3

 1     4657    366     text that^has some line^breaks [end text]
 2     45      264     more text that has^line breaks [end text]