通常,grep搜索所有包含与我指定的模式/参数匹配的行。
我只想匹配模式(即不是整行)。
因此,如果文件包含以下行:
We said that we'll come.
Unfortunately, we were delayed.
Now, we're on our way.
Didn't I say we'd come?
我想找到所有以“we”开头的缩写(正则表达式模式:)we\'[a-z]+/i
;我正在寻找输出:
we'll
we're
we'd
我该如何做(使用grep或其他 Unix/Windows 命令行工具)?
答案1
使用-o
选项:
grep -E -i -o "we'[a-z]+" file.txt
但请注意,这并不是可以普遍移植到所有grep
实现的。
答案2
我更喜欢用 Perl 来实现这样的功能:
#!/usr/bin/perl
use strict;
use warnings;
open FH, "< parse.txt" or die $!;
while(<FH>)
{
while($_ =~ /\b(we\'\w+)\b/g)
{
print $1."\n";
}
}
close FH;
输入文本:
Some text we're test we'll why we're.
More text we'll we're.
Test.
输出:
we're
we'll
we're
we'll
we're