dsg41888 2015-08-17 04:50
浏览 69
已采纳

转到lang区分“ ”和换行符

I am trying read certain string output generated by linux command by the following code:

out, err := exec.Command("sh", "-c", cmd).Output()

The above out is of []byte type, how can I differentiate the " " character contained in line content with the real line break? I tried

strings.Split(output, "
")

and

bufio.NewScanner(strings.NewReader(output))

but they both split the whole string buffer whenever seeing a " " character.

OK, to clarify, an "unreal" break is a " " character contained in a string as follows, Print first result: "123; 234; " Print second result: "456; "

The whole output is one big multi-line string, it may also contain some other quoted strings, and I am processing the whole string output in my go program, but I can't control the command output and add a back slash before the " " character.

Further clarify: I meant to process byte sequence which contains string of strings, and want to preserve the " " contained in the inner string and use the the outer layer " " to break lines. So for the following byte sequence:

First line: "test1"
Second line: "123;
234;
345;"
Third line: "456;
567;"
Fourth line: "test4"

I want to get 3 lines when processing the whole sequence, instead of getting 7 total lines. It's a old project, but I remember I can use Python to directly get 3 lines using syntax like "for line in f", and print the content of second inner string instead of rendering it.

  • 写回答

2条回答 默认 最新

  • doufei16736 2015-08-18 02:19
    关注

    There is no distinction between a "real" and an "unreal" line break.

    If you're using a Unix-like system, the end of a line in a text file is denoted by the LF or ' ' character. You cannot have a ' ' character in the middle of a line.

    A string in memory can contain as many ' ' characters as you like. The string "foo bar ", when written to a text file, will create two lines, "foo" and "bar".

    There is no effective difference between

    fmt.Println("foo")
    fmt.Println("bar")
    

    and

    fmt.Printf("foo
    bar
    ")
    

    Both print the same sequence of 2 lines, as does this:

    fmt.Println("foo
    bar")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog