Ruby ruby 脚本处理文件去重复行

icemark · May 02, 2012 · Last by icemark replied at May 07, 2012 · 5723 hits

大家如何写这个 ruby 脚本呢? 当然在 linux 上可以调用 shell 里面 uniq file 就可以完成任务了 如果是在 windows 执行 ruby 脚本如何写呢? 下面 google 得到的脚本 会把分行全部搞乱掉,

# print file and remove duplicate, non-consecutive lines from a file (careful of memory!)
     $  ruby -e 'puts STDIN.readlines.sort.uniq!.to_s' < file.txt

Unknow user #1 May 02, 2012

维护一个 SET,然后判断是否已有此行,没有就加进去 如果觉得效率低可以同时维护个 SET 来存字符串的 hash。 好吧。。我知道效率很低..

读取文件内容,用 split 分割各行到数组中,然后用数组的去除重复行

#2 楼 @y2950896 File.read(fname).split("\n").uniq

#3 楼 @huacnlee 简化一下 File.readlines(fname).uniq

$ ruby -e 'STDIN.readlines.uniq.each{|l|print l}' <test.txt

#4 楼 @fsword

楼主想要的应该是一个命令行下的解决方案,我给个完整的:

ruby -i -e 'puts ARGF.readlines.uniq!' file.txt

谢谢各位 我最后用的是 @fsword 的 File.readlines(fname).uniq 是 ok 的

You need to Sign in before reply, if you don't have an account, please Sign up first.