在 julia 中查找替换文件内容的正确方法是什么?
what is the correct way to find replace content of a file in julia?
我正在尝试评论除所需文件 ID 之外的所有 ID。
ids.txt的内容:
name="app1"
id="123-45-678-90"
#id="234-56-789-01"
#id="345-67-890-12"
#id="456-78-901-23"
#id="567-89-012-34"
#id="678-90-123-45"
write_correct_id.jl的内容:
#required id
req_id = "id=\"456\-78\-901\-23\""
#read file content to array
ids_array
open("/path/to/ids.txt", "r") do ids_file
ids_array = readlines(ids_file)
end
#comment all lines starting with "id =" and un-comment the line with required id
id_pattern ="^id="
id_regex = Regex(id_pattern)
for line in ids_array
if occursin(id_regex, line)
replace (line, "id" => "#id")
elseif occursin(req_id, line)
replace(line, "#$req_id" => "req_id)
end
end
#write back the modified array to the file
open("/path/to/ids.txt", "w") do ids_file
for line in ids_array
write("$line\n")
end
end
id开头的元素(即.^id=)无法识别。
请帮帮我!
您的代码存在问题,即字符串在 Julia 中是不可变的,因此 replace
不会改变字符串而是创建一个新字符串。
这是我的建议,我将如何编写您的代码(请注意我的实现中的一些其他小差异,例如 count
确保我们只进行一次替换,因为一般来说,某些模式可能会多次出现行;在您的用例中,startswith
通常也应该比 occursin
快:
req_id = "id=\"456-78-901-23\""
id_pattern = "id="
lines = readlines("idx.txt")
open("idx.txt", "w") do ids_file
for line in lines
if startswith(line, "#$req_id")
println(ids_file, replace(line, "#$req_id" => req_id, count=1))
# or even:
# println(ids_file, chop(line, head=1, tail=0))
elseif startswith(line, id_pattern)
println(ids_file, replace(line, "id" => "#id", count=1))
# or even:
# println(ids_file, "#"*line)
else
println(ids_file, line)
end
end
end
我正在尝试评论除所需文件 ID 之外的所有 ID。
ids.txt的内容:
name="app1"
id="123-45-678-90"
#id="234-56-789-01"
#id="345-67-890-12"
#id="456-78-901-23"
#id="567-89-012-34"
#id="678-90-123-45"
write_correct_id.jl的内容:
#required id
req_id = "id=\"456\-78\-901\-23\""
#read file content to array
ids_array
open("/path/to/ids.txt", "r") do ids_file
ids_array = readlines(ids_file)
end
#comment all lines starting with "id =" and un-comment the line with required id
id_pattern ="^id="
id_regex = Regex(id_pattern)
for line in ids_array
if occursin(id_regex, line)
replace (line, "id" => "#id")
elseif occursin(req_id, line)
replace(line, "#$req_id" => "req_id)
end
end
#write back the modified array to the file
open("/path/to/ids.txt", "w") do ids_file
for line in ids_array
write("$line\n")
end
end
id开头的元素(即.^id=)无法识别。
请帮帮我!
您的代码存在问题,即字符串在 Julia 中是不可变的,因此 replace
不会改变字符串而是创建一个新字符串。
这是我的建议,我将如何编写您的代码(请注意我的实现中的一些其他小差异,例如 count
确保我们只进行一次替换,因为一般来说,某些模式可能会多次出现行;在您的用例中,startswith
通常也应该比 occursin
快:
req_id = "id=\"456-78-901-23\""
id_pattern = "id="
lines = readlines("idx.txt")
open("idx.txt", "w") do ids_file
for line in lines
if startswith(line, "#$req_id")
println(ids_file, replace(line, "#$req_id" => req_id, count=1))
# or even:
# println(ids_file, chop(line, head=1, tail=0))
elseif startswith(line, id_pattern)
println(ids_file, replace(line, "id" => "#id", count=1))
# or even:
# println(ids_file, "#"*line)
else
println(ids_file, line)
end
end
end