Ruby,如何将一个文件中的字符串与另一个文件匹配并打印匹配的字符串

时间:2022-09-06 13:13:16

I have two files. File1:

我有两个文件。文件1:

ruby,amazing,awesome

file2:

文件2:

ruby-443-543-fx\n
amazing-122-454-nx\n
hello-432-544-lx\n
awesome-522-65-nx\n

How to do I run a search to match file1 word with file2 line (for example, amazing from file1 to be matched with amazing-122-454-nx)? Then, I need to print the matched results as followings:

如何运行搜索以匹配file1单词和file2行(例如,从file1惊人地匹配惊人的122-454-nx)?然后,我需要打印匹配的结果如下:

ruby-443-543-fx\n
amazing-122-454-nx\n
awesome-522-65-nx\n

2 个解决方案

#1


0  

Here's one way:

这是一种方式:

words = File.read("file1.txt").strip.split(/,/)
words_regex = Regexp.union(words)

File.open("file2.txt").each do |line|
    puts line if line =~ words_regex
end

Output:

输出:

ruby-443-543-fx
amazing-122-454-nx
awesome-522-65-nx

#2


1  

If you convert your file1 to be a one-per-line list of words you want to search for, you can just use grep, the friendly Unix-y searching tool:

如果将file1转换为要搜索的单行列表,则可以使用友好的Unix-y搜索工具grep:

grep -f file1 file2

This will certainly be faster than anything you could build in Ruby.

这肯定比你在Ruby中构建的任何东西都要快。

If you want to remove newlines from the result, you can do that with the tr command, like so:

如果要从结果中删除换行符,可以使用tr命令执行此操作,如下所示:

grep -f file1 file2 | tr -d "\n"

#1


0  

Here's one way:

这是一种方式:

words = File.read("file1.txt").strip.split(/,/)
words_regex = Regexp.union(words)

File.open("file2.txt").each do |line|
    puts line if line =~ words_regex
end

Output:

输出:

ruby-443-543-fx
amazing-122-454-nx
awesome-522-65-nx

#2


1  

If you convert your file1 to be a one-per-line list of words you want to search for, you can just use grep, the friendly Unix-y searching tool:

如果将file1转换为要搜索的单行列表,则可以使用友好的Unix-y搜索工具grep:

grep -f file1 file2

This will certainly be faster than anything you could build in Ruby.

这肯定比你在Ruby中构建的任何东西都要快。

If you want to remove newlines from the result, you can do that with the tr command, like so:

如果要从结果中删除换行符,可以使用tr命令执行此操作,如下所示:

grep -f file1 file2 | tr -d "\n"