在julia中查找文件替换内容的正确方法是什么?

时间:2019-05-08 13:36:50

标签: regex file-io julia pcre

我正在尝试注释除文件所需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 =)开头的元素。

请帮助我!

1 个答案:

答案 0 :(得分:1)

代码中的问题是字符串在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