Home > Backend Development > Golang > How to Preserve Inner String Breaks When Splitting Go Strings with Newlines?

How to Preserve Inner String Breaks When Splitting Go Strings with Newlines?

Linda Hamilton
Release: 2024-12-10 21:58:15
Original
1004 people have browsed it

How to Preserve Inner String Breaks When Splitting Go Strings with Newlines?

Differentiating Newlines in Go: Preserving Inner String Breaks

When reading output from Linux commands using exec.Command, the resulting byte array may contain both literal newline characters ("n") and escaped newlines ("\n"). This can pose a challenge when trying to split the output into lines while preserving inner string breaks.

One approach is to replace escaped newlines with actual newlines using the following line:

strings.Replace(out, `\n`, "\n", -1)
Copy after login

By doing this, we effectively convert the escaped newlines to their original form, allowing us to split the output into lines using standard methods such as:

lines := strings.Split(out, "\n")
Copy after login

This will result in the output being split into lines, but the breaks within strings will be preserved. For example, consider the following output:

First line: "test1"
Second line: "123;\n234;\n345;"
Third line: "456;\n567;"
Fourth line: "test4"
Copy after login
Copy after login

Splitting this output using the above technique will result in the following lines:

First line: "test1"
Second line: "123;\n234;\n345;"
Third line: "456;\n567;"
Fourth line: "test4"
Copy after login
Copy after login

As you can see, the inner string breaks are preserved, and the output is correctly split into lines.

The above is the detailed content of How to Preserve Inner String Breaks When Splitting Go Strings with Newlines?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template