gpt4 book ai didi

Ruby - 仅删除文件中的特定重复行

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:46 26 4
gpt4 key购买 nike

我想从文件中删除重复行,但只删除与特定正则表达式匹配的重复行,而将所有其他重复项留在文件中。这是我目前拥有的:

unique_lines = File.readlines("Ops.Web.csproj").uniq do |line|    
line[/^.*\sInclude=\".*\"\s\/\>$/]
end

File.open("Ops.Web.csproj", "w+") do |file|
unique_lines.each do |line|
file.puts line
end
end

这将正确删除重复行,但只会将满足正则表达式的行添加回文件中。我需要将文件中的所有其他行原样添加回去。我知道我在这里遗漏了一些小东西。想法?

最佳答案

试试这个:

lines = File.readlines("input.txt")
out = File.open("output.txt", "w+")
seen = {}

lines.each do |line|
# check if we want this de-duplicated
if line =~ /Include/
if !seen[line]
out.puts line
seen[line] = true
end
else
out.puts line
end
end

out.close

演示:

➜  12980122  cat input.txt
a
b
c
Include a
Include b
Include a
Include a
d
e
Include b
f
➜ 12980122 ruby exec.rb
➜ 12980122 cat output.txt
a
b
c
Include a
Include b
d
e
f

关于Ruby - 仅删除文件中的特定重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com