Published on :
Utility CREATION_INTERNE

Execute a system command and capture output into a dataset

This code is also available in: Deutsch Español Français
Awaiting validation
Attention : This code requires administrator privileges.
The `%cmd2ds` macro takes two parameters: `cmd` (the system command to execute) and `dsout` (the name of the output dataset, defaulting to `_cmd2ds`). It uses the `filename ... pipe` interface to execute the command and redirect its standard output. A DATA STEP then reads each line of this output and stores it in a 256-character `str` variable in the specified dataset. The `filename` reference is then cleared, which is crucial for system resources.
Data Analysis

Type : CREATION_INTERNE


The output dataset is created dynamically by reading the standard output of a system command executed via the 'pipe' interface. Each output line from the command becomes an observation in the SAS dataset.

1 Code Block
DATA STEP Data
Explanation :
This block defines the `%cmd2ds` macro. It manages the output dataset name by assigning a default value of `_cmd2ds` if `dsout` is not specified. The `filename _cmd2ds pipe "&cmd";` declaration is crucial as it executes the system command provided by the `&cmd` parameter and associates its output with the fileref `_cmd2ds`. The `DATA STEP` then reads this output line by line using `infile _cmd2ds;` and `input;`, assigning each line to the `_infile_` variable and then to the `str` variable, thereby creating the SAS dataset. Finally, `filename _cmd2ds CLEAR;` clears the fileref, closing the pipe and releasing system resources.
Copied!
1%put MACRO CALLED: cmd2ds v1.0;
2 
3%macro cmd2ds(cmd,dsout);
4 %IF not %LENGTH(&dsout) %THEN %let dsout=_cmd2ds;
5 filename _cmd2ds pipe "&cmd";
6 DATA &dsout;
7 LENGTH str $ 256;
8 INFILE _cmd2ds;
9 INPUT;
10 str=_infile_;
11 RUN;
12 filename _cmd2ds CLEAR;
13%mend cmd2ds;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : This is public domain software. No guarantee as to suitability or accuracy is given or implied. User uses this code entirely at their own risk.