我正在尝试在 FileB(以逗号分隔)中搜索包含 FileA 中行内容的行。我最初尝试使用 grep
但它似乎并不关心 FileA 中的某些字符。我不认为 CSV 格式很重要,至少对 grep
来说是这样。
$ grep -f FileA FileB
grep: Unmatched [ or [^
我愿意使用任何普遍可用的 Linux 命令、Perl 或 Python。没有可以匹配的特定表达式,这就是使用 FileA 中的内容进行匹配的原因。下面是我们想要在 FileB 中匹配的 FileA 中的一些示例行。
page=--&id='`([{^~
page=&rows_select=%' and '%'='
l=admin&x=&id=&pagex=http://.../search/cache?ei=utf-&p=change&fr=mailc&u=http://sub.domain.com/cache.aspx?q=change&d=&mkt=en-us&setlang=en-us&w=afe,dbfcd&icp=&.intl=us&sit=dbajdy.alt
fileB 中包含上述字符串的行将在该行中包含其他字符,即两个文件的字符串将不会一对一匹配:
fileA包含abc
,fileB包含012abc*()
,012abc*()
会打印
最佳答案
一个简单的 python 解决方案是:
with open('filea', 'r') as fa:
with open('fileb', 'r') as fb:
patterns = fa.readlines()
for line in fb:
if line in patterns:
print line
这会将整个模式文件存储在内存中,并将其他文件的每一行与列表进行比较。
但是你为什么不直接使用diff
呢?我必须查看联机帮助页,但我很确定有一种方法可以让它说明两个文件之间的相似之处。谷歌搜索后:
- Using diff to find the portions of many files that are the same? (bizzaro-diff, or inverse-diff)
- https://unix.stackexchange.com/questions/1079/output-the-common-lines-similarities-of-two-text-files-the-opposite-of-diff
他们给出了解决方案:
diff --unchanged-group-format='@@ %dn,%df
%<' --old-group-format='' --new-group-format='' \
--changed-group-format='' a.txt b.txt
关于regex - 根据源文件内容解析目标文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088482/