bash - grep 从两个文件中反向读取匹配模式
问题描述
我有一个文件(请注意,有些行超过 2 列,有些行是 1 个空格分隔的,有些是多个空格分隔的,这个文件很大......)
file1.txt:
there is a line here that has more than two columns
## this line is a comment
blahblah: blahblahSierraexample7272
foo: foo@foobar.com
nonsense: nonsense59s59S
nonsense: someRandomColumn
.....
我有另一个文件,它是 file1.txt 的子集,该文件只有两列,列是“1”空格分隔的!
file2.txt
foo: foo@foo.com
nonsense: nonsense59s59S
现在,我想从 file1.txt 中删除 file2.txt 中出现的所有行,如何在 shell 脚本中执行此操作?请注意,第二个文件(file2.txt)只有两列,而 file1.txt 有多个......所以如果需要进行匹配,它应该是:$1(from file2) match $1(from file1)
然后$NF(from file2) match $NF(from file1)
反转匹配并打印......
PS 已经尝试过grep -vf file2.txt file1.txt
了,但是由于 column1 和 $NF 之间的空间没有固定,所以它不起作用...... sed 和 awk 应该可以解决问题,但无法提供代码......
sed -i '/^<firstColumnOfFile2> .* <lastColumnOfFile2>$/d' file1.txt (perhaps in a while loop!)
或类似的东西:grep -vw -f ^[(1stColofFile2)] and also [(lastColOfFile2)]$ file1.txt
解决方案
您可以使用sed
将行file2.txt
转换为与冒号后的一个或多个空格匹配的正则表达式,然后用于grep
从file1.txt
匹配的行中删除这些行:
$ grep -Evf <(sed 's/^\([^:]*\): /^\1:[[:space:]]+/' file2.txt) file1.txt
there is a line here that has more than two columns
## this line is a comment
blahblah: blahblahSierraexample7272
foo: foo@foobar.com
nonsense: someRandomColumn
推荐阅读
- git - 将代码从分支推送到git中的主分支的正确方法?
- c# - RichTextBox.GetCharFromPosition 在使用文本框尺寸时返回不正确的字符
- amazon-web-services - 使用 Boto3 和 Create_Pipeline 时,PipelineActivity 的错误必须只有一个成员
- react-native - React Native Navigation 重新加载 Stack Navigator 主屏幕
- javascript - 如何更改浏览器中 document.cookie 中显示的值?
- c# - 使用 c# 通过 SMTP 邮件协议发送位图图像,显示损坏的图像
- c# - Selenium 在尝试查找选项时抛出 NoSuchElementException,即使该选项存在
- javascript - 谷歌地图在点上自动居中
- excel - 使用变量路径打开文件夹
- anaconda - 带有fortran扩展的python包的conda-forge配方不适用于appveyor