我试图理解为什么以下内容没有给我我认为(或想要:))应该返回的内容:
sed -r 's/^(.*?)(Some text)?(.*)$/\2/' list_of_values
或 Perl:
perl -lpe 's/^(.*?)(Some text)?(.*)$/$2/' list_of_values
所以我希望我的结果是
只是Some text
$2
中没有捕获任何内容)那么它应该是空的。我确实注意到,对于
perl,如果 Some text
位于行/字符串的开头(这让我感到困惑......),它 does
可以工作。 (还注意到删除
^
和
$
没有效果)基本上,我正在尝试获取
grep
将通过
--only-matching
选项返回的内容,如此处所述。只有我想/需要在正则表达式中使用 sub/replace 。
已编辑(添加示例数据)
输入示例:
$ cat -n list_of_values
1 Black
2 Blue
3 Brown
4 Dial Color
5 Fabric
6 Leather and Some text after that ....
7 Pearl Color
8 Stainless Steel
9 White
10 White Mother-of-Pearl Some text stuff
所需输出:
$ perl -ple '$_ = /(Some text)/ ? $1 : ""' list_of_values | cat -n
1
2
3
4
5
6 Some text
7
8
9
10 Some text
this 展示了如何使用 Perl 复制 grep -o
。
s/^(.*?)(Some text)?(.*)$/$2/
foo Some text bar
012345678901234567
结果只是一个空字符串而不是
Some text
嗯,
^
匹配 0 个字符。
(.*?)
匹配 0 个字符。
(Some text)?
匹配 0 个字符。
(.*)
匹配 17 个字符。
$
匹配 0 个字符。
s{^ .*? (?: (Some[ ]text) .* | $ )}{ $1 // "" }xse;
或
s{^ .*? (?: (Some[ ]text) .* | $ )}{$1}xs; # Warns if warnings are on.
更简单:
$_ = /Some text/ ? $& : "";
-p
的使用。您确定要为每行输入输出一行吗?在我看来你宁愿拥有
perl -nle'print $& if /Some text/'