linux - perl grep 和 cli grep 之间的不一致

标签 linux perl grep

我正在做以下事情:

#!/usr/bin/perl  
use strict;  
use warnings;  

my $proc = `ps -ef|grep -c myscriptname`;  
print $proc;  

当我在脚本中运行它时,它会打印 2。

ps -ef|grep -c myscriptname 在命令行上只显示:1
为什么?

同样适用于 my $proc = qx/ps -ef|grep -c myscriptname/

更新
明确地说,我从 somerandomscript.pl

运行这个片段

更新 2
按照 edorqui 的建议,我删除了 -c 获取:

12013 15777 15776 0 14:11 pts/6 00:00:00 sh -c ps -ef | grep myscriptname   
12013 15779 15777 0 14:11 pts/6 00:00:00 grep myscriptname Argument "12013 15777 15776 0 14:11 pts/6 00:00:00 sh -c ps..." isn't numeric in numeric gt (>) at somerandomscript.pl line 8  

从脚本内部

最佳答案

ps -ef 命令显示了 grep 本身。

要跳过此行为,请尝试对与 grep 本身不匹配的正则表达式条件进行 grepping:

ps -ef | grep myscript[n]ame

或任何类似的东西:

ps -ef | grep myscriptnam[e]

说明

如果你在后台运行一个sleep命令:

$ sleep 100 &
[1] 9768

然后用ps -ef寻找它:

$ ps -ef | grep sleep
me    9768  3673  0 14:00 pts/6    00:00:00 sleep 100
me    9771  3673  0 14:00 pts/6    00:00:00 grep --color=auto sleep

你得到两行:进程本身和寻找它的 grep 命令。为了避免它并只显示过程本身,我们可以:

$ ps -ef | grep -v grep | grep sleep

或者在代码中使用正则表达式,使得grep进程不匹配:

$ ps -ef | grep slee[p]
me    9768  3673  0 14:00 pts/6    00:00:00 sleep 100

因为行

me    9771  3673  0 14:00 pts/6    00:00:00 grep --color=auto sleep

grep slee[p] 中不匹配。

See explanation in a related topic .

关于linux - perl grep 和 cli grep 之间的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18146050/

相关文章:

mysql - 如何加密整个列

Perl:文件输入到排序的文件

bash - ff探针 |展架 |数据包大小 |划分 |添加

perl - JSON 数据和 DBIx::Class - 如何直接存储数据?

regex - 如何独立于字符串中各自的位置匹配两个值

linux - 在文件列表中查找正则表达式

bash - 如何grep唯一出现的次数

c - Visual Studio Code 忽略调试符号

linux命令根据模式将大型csv文件随机排列以交替行

linux - 无法连接 ssh sh : 6000: command not found