我有这个文本文件,我想排除"access“这个词,因为a后面跟着第二、第三或第四位置的a、b或c。
# cat tt.txt
access
ample
taxing
我试过了,但它会返回所有三个单词。
# grep '[a-c][^a-c][^a-c][^a-c]' tt.txt
access
ample
taxing
更新1:
我使用了上面过于简化的例子。
# cat tt.txt
access
bccess
ample
taxing
tacking
not
# grep -Ev '[a-c].{0,2}[a-c]' tt.txt
ample
taxing
not
# grep -E '[a-c].{0,2}[^a-c]' tt.txt
access
bccess
ample
taxing
tacking
# Expected
ample
taxing
发布于 2022-10-18 21:35:50
我想排除
access
一词,因为a
后面跟着a
,b
或c
位于第二、第三或第四位。
可以使用这个awk
来完成
awk '/[a-c]/ && !/[a-c].{0,2}[a-c]/' file
ample
taxing
RegEx分解:
[a-c]
:匹配a
或b
或c
.{0,2}
:匹配任何characters[a-c]
:匹配a
或b
或c
的0到2
或者在gnu-grep
中使用查找器
grep -P '^(?=.*[a-c])(?!.*[a-c].{0,2}[a-c])' file
ample
taxing
perl
中的同一解
perl -ne 'print if /[a-c]/ && !/[a-c].{0,2}[a-c]/' file
发布于 2022-10-25 13:48:14
据我所知,你的情况是:
c
.
a
、b
或a
pos 0-3之一,不能在另一个abc.之前使用abc。
那么,我们为什么不这样写代码呢。
use strict;
use warnings;
while (<DATA>) {
next unless /[a-c]/; # skip if no abc
next if substr($_, 0, 4) =~ /(?<=[a-c])[a-c]/; # skip if an abc is preceded by an abc
print; # otherwise print
}
__DATA__
access
bccess
ample
taxing
tacking
not
这是一种编写模拟菱形操作符<>
的代码的方法,这是-n
和-p
开关常用的Perl使用的。我们使用数据文件句柄来模拟一个文件。如果你想把它变成一个单线绳,它看起来就像
$ perl -ne' next unless /[a-c]/; next if substr($_, 0, 4) =~ /(?<=[a-c])[a-c]/; print; ' file.txt
我已经在你的示例单词列表上测试过了,它似乎像预期的那样工作。
https://stackoverflow.com/questions/74120133
复制相似问题