Go lang differentiate “\n” and line break

后端 未结 2 614
陌清茗
陌清茗 2021-01-06 05:27

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

out, err := exec.Command(\"sh\", \"-c\", cmd).Output()
相关标签:
2条回答
  • 2021-01-06 05:51

    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 '\n' character. You cannot have a '\n' character in the middle of a line.

    A string in memory can contain as many '\n' characters as you like. The string "foo\nbar\n", 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\nbar\n")
    

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

    fmt.Println("foo\nbar")
    
    0 讨论(0)
  • 2021-01-06 06:09

    It's possible that your "\n" is actually the escaped version of a line break character. You can replace these with real line breaks by searching for the escaped version and replacing with the non escaped version:

    strings.Replace(sourceStr, `\n`, "\n", -1)

    Since string literals inside backticks can be written over multiple lines, Go escapes any line break characters it sees.

    0 讨论(0)
提交回复
热议问题