Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find line breaks from MATLAB system command

I'm trying to parse the result string from a system command to an external program.

[status,result] = system(cmd);

result prints out on my console with its lines correctly broken out, i.e.

line1

line2

...

But it's actually just a single long character array, and there are no newline characters anywhere. How does matlab know when to print out a new line? And how can I separate the char array into its separate lines for further parsing. Thanks!

like image 282
genekogan Avatar asked Feb 05 '12 21:02

genekogan


People also ask

How do you do a line break in MATLAB?

c = newline creates a newline character. newline is equivalent to char(10) or sprintf('\n') . Use newline to concatenate a newline character onto a character vector or a string, or to split text on newline characters.

What does \r do in MATLAB?

There exactly one carriage return character, in MATLAB represented by the escaped character \r. Several of these (and combinations thereof) have been used to indicate a newline in a text file, but a newline standard is not the same thing as a carriage return character.

How do I find a string in MATLAB?

k = strfind( str , substr ) searches the string str for occurrences of the substring substr . The operator returns a vector that contains the starting index of each occurrence of substr in str . The search is case-sensitive.

How do I split a string into a new line?

Split String at NewlineCreate a string in which two lines of text are separated by \n . You can use + to concatenate text onto the end of a string. Convert \n into an actual newline character. Although str displays on two lines, str is a 1-by-1 string containing both lines of text.


2 Answers

Depending on operation system different characters represent end of line. It can be \n, \r, \f or their combination. Those characters have ASCII code less then 30. So you can look for them with, for example, find(results < 30) to display their position in the string , and int32(results(results < 30)) to see their code.

int32(sprintf('\n\r\f'))

ans =

      10          13          12

Then you can use the code you get to split the string:

regexp(results, char(13), 'split')

If you are not interested on which characters are used as end-of-line, you can just try:

regexp(results, '[\f\n\r]', 'split')
like image 116
yuk Avatar answered Nov 15 '22 01:11

yuk


Further to Andrey's answer, you can split the string into a cell array using the following command:

split_result = regexp(result, '\n', 'split');

This uses regular expressions to split the string at each newline character.

You can then access each line of the system command output using:

 split_result{index}
like image 40
Bill Cheatham Avatar answered Nov 15 '22 01:11

Bill Cheatham