如何在除第一列之外的整个文本中使用"grep -v"或类似的东西?



我正在尝试操作一个文件,比如:

76ers23 Philadelphia 76ers announced today that
76ers24 Lakers announced today 
76ers25 blazers  plays today 
76ers26 celics announced today that
76ers27 Bonston has Day off
76ers28 Philadelphia 76ers announced today that
76ers29 the blazzers announced today that
76ers30 76ers Training day
76ers31 Philadelphia 76ers has a day off  today 
76ers32 Philadelphia 76ers  humiliate Lakers 
76ers33 celics announced today that

我想从第二列中删除所有包含术语76人的条目,以便获得:

76ers24    Lakers announced today 
76ers25    blazers  plays today 
76ers26    celics announced today that
76ers27    Bonston has Day off
76ers29    the blazzers announced today that
76ers33    celics announced today that

我的问题是,如果我使用grep -v "76ers",它会返回null

我只想在第二行中使用grep(或其他命令(。

我发现了这种复杂的方法,但这正是我想要的,但我在第二列的开头得到了一个_

cat file|awk '{print $1}' >file1
cat file|awk '{$1="";print $0}'|tr -s ' ' | tr ' ' '_' >file2
paste file1 file2 |grep -v "_76ers"

我不是狂欢专家,所以我想会有一个更简单的方法。提前谢谢!

使用跳过第一列的正则表达式。

grep -v '^[^ ]* .*76ers' file

[^ ]*将所有内容匹配到第一个空间。

使用awk:

awk '{ found=0;for(i=2;i<=NF;i++) { if (match($i,"76ers")) { found=1 } } if (found==0) { print $0 } }' file

循环通过第二个空格分隔的字段到最后一个字段,并使用match检查该字段是否包含76人。如果是,请设置一个已找到的标志。在我们循环遍历每行的每个字段后,如果发现行为0,则仅打印该行。。

您可以创建一个Extend Reqular Expression来忽略第一列。不知道你到底在说什么;风味";操作系统的是,我将给您两种不同的格式。

grep -Eegrep相同
[[:digit:]][0-9]相同
[[:space:]][相同]

第一个选项:寻找后面有空白的76人:
grep -Ev '76ers[[:space:]]' <file>

第二个选项:寻找76人,后面跟着一个或多个数字,然后是第二个76人:
grep -Ev '76ers[[:digit:]][[:digit:]]*.*76ers' <filename>

使用GNU grep,要求匹配为"全词";带有-w/--word-regexp选项:

grep -vw '76ers' infile

来自手册:

-w
--word-regexp
仅选择那些包含构成完整单词的匹配项的行。这个测试是匹配的子字符串必须位于行,或前面有一个非单词组成字符。类似地,它必须在行的末尾或后面跟一个非单词构成特征。单词组成字符是字母,数字和下划线。如果-x也是指定。

这里有一种使用awk的替代方法。与Balmer的想法类似,确保第一列与ERE不匹配。

$ awk -v ere='76ers' '$0~ere && $1!~ere' file

这将打印与正则表达式ere($0~ere(匹配的所有记录/行,但仅当第一列与该正则表达式$1!~ere不匹配时。

$ grep -v ' .*76ers' file
76ers24 Lakers announced today
76ers25 blazers  plays today
76ers26 celics announced today that
76ers27 Bonston has Day off
76ers29 the blazzers announced today that
76ers33 celics announced today that

最新更新