[英]Comparing two files at end of line in Linux
I would like to compare two files and get the output of matching string in one of the files at the end of the line: 我想比较两个文件,并在行尾的一个文件中获取匹配字符串的输出:
Let's say I have two files:- 假设我有两个文件: -
file1: 文件1:
xyzabcdef
xyz
abcdefghi
file2: 文件2:
fghjkl
wertyu
abcdef
I could do something like this: 我可以这样做:
grep -Fif file2 file1
This gives me the following output: 这给了我以下输出:
xyzabcdef
abcdefghi
This is because abcdef in file2 matches both of those lines in file1. 这是因为file2中的abcdef匹配file1中的这两行。 However, what I would like is to just compare the end of the line in file1 to those in file2.
但是,我想要的是将file1中的行尾与file2中的行的末尾进行比较。 So, I would like output to be:
所以,我想输出为:
xyzabcdef
Is there some magic command that will let me do this? 是否有一些神奇的命令可以让我这样做?
Extending Lars's solution which I think the best option. 扩展Lars的解决方案,我认为这是最好的选择。 Simply use the following:
只需使用以下内容:
cat -E file2 | grep -if - file1
The trick is to use -E
option of cat
to append $
at the end of each line. 诀窍是使用
cat
-E
选项在每行的末尾附加$
。 Then read the pattern from stdin using -
option of grep. 然后阅读使用标准输入模式
-
的grep的选项。 Also you have to use regex matching, so I removed the -F
. 你还必须使用正则表达式匹配,所以我删除了
-F
。
I would append $
to each line of file2 and use the command grep -if file2 file1
. 我会将
$
追加到file2的每一行,并使用命令grep -if file2 file1
。
The $
is a regex and means "match at the end of the line". $
是一个正则表达式,意思是“在行尾”匹配。 The option -F
would use fixed string mode that is incompatible with regex, thus omit this option. 选项
-F
将使用与正则表达式不兼容的固定字符串模式,因此省略此选项。
You can do it simply by reading each line in file2
and using each line as a search term for grep
anchoring the term to the end of line with $
, eg: 你可以简单地通过读取
file2
中的每一行并使用每一行作为grep
的搜索术语来将该术语锚定到$
行的末尾,例如:
$ while read -r line; do grep "${line}$" file1; done <file2
xyzabcdef
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.