开发者

How do i remove "new line" from a command that ends in | wc -l in perl

开发者 https://www.devze.com 2023-01-07 12:21 出处:网络
ps efax 2>/dev/null|grep firstbo|grep -v grep|wc -l if i store this as a scalar, then, the scalar contains a new lin开发者_JS百科e, how do i remove the new linechomp $scalar;

ps efax 2>/dev/null|grep firstbo|grep -v grep|wc -l

if i store this as a scalar, then, the scalar contains a new lin开发者_JS百科e, how do i remove the new line


chomp $scalar;

But everything after the ps can be done more efficiently inside your script, like this:

my $count = 0;
open(my $ps, "ps -e -o comm |") or die "failed to spawn ps: $!";
while(<$ps>) {
    $count++ if /firstbo/;
}
close $ps;


chomp $scalar will eat the newline


Use the chomp operator. You can also condense your command by taking advantage of the fact that the re in grep stands for regular expression:

chomp(my $num_firstbo = `ps efax 2>/dev/null | grep [f]irstbo | wc -l`);

By matching against a singleton character class, the command above matches processes whose argvs contain firstbo, but not the grep command itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消