Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Is it possible to convert a raw string literal to an interpreted string literal?

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.

like image 849
Tshaka Eric Lekholoane Avatar asked Sep 19 '20 16:09

Tshaka Eric Lekholoane


2 Answers

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?

like image 74
icza Avatar answered Oct 22 '22 17:10

icza


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"

like image 1
Nima Sarayan Avatar answered Oct 22 '22 16:10

Nima Sarayan