使用正则表达式从 ps 输出中 grep 部分文本

grep part of text from ps output with regex

ps -ef命令输出-Dorg.xxx.yyy=/home/user/aaa/server.log

我想提取文件路径/home/user/aaa/server.log(可以是任何name.file)。

现在,我正在使用命令:

ps -ef | grep -Po '(?<=-Dorg.xxx.yyy=)[^\s]*'

它将显示两个匹配的结果:

/home/user/aaa/server.log
)[^\s]*

看起来它也计算了第二个匹配结果的命令。我怎样才能删除它?或者有其他建议吗? (我不能用-m1)。

使用那个:

grep -Po '(?<=-[D]org.xxx.yyy=)[^\s]*'

只需将其中一个字符放在方括号中 ([D])。正则表达式的含义没有改变,模式不再匹配自身。

如果只需要文件名,使用\K运算符:

org\.xxx\.yyy=\K[^\s]*

ps -ef | grep -Po 'org\.xxx\.yyy=\K[^\s]*'

它将匹配整个字符串,但只会打印与[^\s]*匹配的文件名。

来自perlre

There is a special form of this construct, called \K (available since Perl 5.10.0), which causes the regex engine to "keep" everything it had matched prior to the \K and not include it in $& . This effectively provides variable-length look-behind.