Is it possible to convert raw string literals to interpreted string literals in Go? (See language specification)
I have a raw string literal, but I want to print out to the console what one would get with an interpreted string literal—that is, text output formatted using escape sequences.
For example, printing this raw string literal gives
s := `\033[1mString in bold.\033[0m`
println(s) // \033[1mString in bold.\033[0m
but I want the same result one would get with
s := "\033[1mString in bold.\033[0m"
println(s) // String in bold. (In bold)
For context, I am trying to print the contents of a text file that is formatted with escape sequences using
f, _ := := ioutil.ReadFile("file.txt")
println(string(f))
but the output is in the former way.
Use strconv.Unquote()
:
s := `\033[1mString in bold.\033[0m`
s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
panic(err)
}
fmt.Println("normal", s2)
This will output:
normal String in bold.
Note that the string
value passed to strconv.Unquote()
must contain wrapping double quotes or backticks, and since the source s
does not contain the wrapping quotes, I pre- and suffixed those like this:
`"` + s + `"`
See related questions:
How do I make raw unicode encoded content readable?
Golang convert integer to unicode character
How to transform Go string literal code to its value?
How to convert escape characters in HTML tags?
First, if you not have raw string you need to write it as raw string and without changes thing like "\n" and others,and incase you want to return bytes:
s := "\033[1mString in bold.\033[0m"
rune := string([]rune(s))
b := []byte(rune)
f, err := os.OpenFile("filename.txt", os.O_RDWR, 0644)
if err != nil {
return err
}
if _, err := f.Write(b); err != nil {
return err
}
with this approach, the bytes don't change so that the sh265 will be the same, and you return it after reading it from the file with no further changes.
second, for reading the data and printing:
bytes, err := os.ReadFile("filename.txt")
if err != nil {
return err
}
s = strconv.Quote(string(bytes))
fmt.Println(s)
and you gone got "\x1b[1mString in bold.\x1b[0m"
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