mojtaba namvaran
mojtaba namvaran

Reputation: 11

Use shell commands from Matlab

I use a Matlab code and want to insert below Bash command between lines to select specific files.

du --max-depth 1 |
awk -v q='"' '$1 < 30000000 && $2 != "." {sub(/^[0-9\t ]+/, "", $0); print q $0 q}'

This command works well in the shell, but I am confused how I can use it between lines of Matlab code.

Upvotes: 1

Views: 540

Answers (2)

LowPolyCorgi
LowPolyCorgi

Reputation: 5170

Just to complete Andras Deak's answer the bang operator would also work:

!du --max-depth 1 |
awk -v q='"' '$1 < 30000000 && $2 != "." {sub(/^[0-9\t ]+/, "", $0); print q $0 q}'

Upvotes: 1

Under linux, system and unix do the same: they evaluate their string argument in the shell. For this you have to escape the single quotes due to MATLAB's string syntax, you do this by doubling each single quote:

[~,output]=system('du --max-depth 1 | awk -v q=''"'' ''$1 < 30000000 && $2 != "." {sub(/^[0-9\t ]+/, "", $0); print q $0 q}''');

This will save the output of your command to the string named output. The first output argument would be a status code. Although, depending on subsequent applications, you might want to drop the double quotes from your output altogether (i.e. omit the variable q and just print $0 at the end).

Since your output is now a character vector, with newlines simply included as the \n character, you have to do some postprocessing to get meaningful file names. The simplest thing to do is to use regexp to split your string at the newlines, and then remembering to throw away the last (empty) string due to the final newline at the end of the string. If you heed my suggestion regarding the double quotes, here's what you do:

[~,output] = system('du --max-depth 1 | awk ''$1 < 30000000 && $2 != "." {sub(/^[0-9\t ]+/, "", $0); print $0}''');
filelist = regexp(output,'\n','split'); %split at newline
filelist = filelist(1:end-1); %throw away the last dubious part

Now filelist is a cell array with each element containing a string: the name of each object output by your script.

Be careful though: often input from the command window will garble the input to a system call, as if from STDIN. See this important post. In principle you can fix some of this issue by redirecting STDIN of your system command to /dev/null, as in du --max-depth 1 </dev/null | awk ..., but I've found that not to be a general solution.

Upvotes: 6

Related Questions