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!
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.
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.
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.
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.
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')
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With