An easy way to parse escaped newline character?

I have a text file in which I specify some Makie plot labels and some of those labels have newline characters in them. I’ve attempted a few different ways to read that text file so that the two character “\n” gets translated into the single ‘\n’ for Makie but none of them have worked I may end up manipulating the vector of UInt8 to parse escaped newline characters, but I am hoping someone knows of an easier way.

I’ve tried the following:

function mweesc()
	# write temp file
	fn = "temp.txt"
	str = """
		  this\\nis
		  a test of escaped\\nnewlines
		  """
	write(fn, str)
	
	# read temp file
	io = IOBuffer()
	open(fn, "r") do f
		nLine = 0
		while !eof(f)
			line = readline(f, keep=true)
			nLine += 1
			println("line $nLine:")
			print("$line")
			println("line[5] = '$(line[5])'")
			str = string("$line")
			print("$str")
			println("str[5] = '$(str[5])'")
			
#			print(io,"$line")
#			v = take!(io)
#			println("v[5] = $(v[5])")
#			str = String(v)
		end # while
	end # open
end

and the output is:

julia> mweesc()
line 1:
this\nis
line[5] = '\'
this\nis
str[5] = '\'
line 2:
a test of escaped\nnewlines
line[5] = 's'
a test of escaped\nnewlines
str[5] = 's'

but I would like str[5] to be ‘\n’ instead of ‘\’.

I’m not sure how exactly you would end up with a string containing "\\n" (i.e. a forward slash and a letter n), but I suppose you could just use replace(..., "\\n" => '\n'). With line = replace(readline(f, keep=true), "\\n" => '\n'), the output becomes

julia> mweesc()
line 1:
this
is
line[5] = '
'
this
is
str[5] = '
'
line 2:
a test of escaped
newlines
line[5] = 's'
a test of escaped
newlines
str[5] = 's'
1 Like

Another way would be to fix on the write side:

fn = "temp.txt"
str = """
	  this\\nis
	  a test of escaped\\nnewlines
	  """
write(fn,join(split(str,"\\n"),'\n'))

or to fix this on the read side:

julia> open(fn, "r") do f
               nLine = 0
               while !eof(f)
                       lines = chomp.(split(readline(f, keep=true),"\\n"))
                       for line in lines
                           nLine += 1
                           println("lines $nLine:")
                           println(line)
                       end
               end # while
       end # open
lines 1:
this
lines 2:
is
lines 3:
a test of escaped
lines 4:
newlines
1 Like