Chinaunix

标题: 这样的文本如何处理? [打印本页]

作者: sunzhiguolu    时间: 2016-11-23 17:43
标题: 这样的文本如何处理?
本帖最后由 sunzhiguolu 于 2016-11-23 22:46 编辑

看了一篇帖子, 内容如下:
问题:如果匹配到行包含 /bin/bash ./ifstat_monitor.sh则就打印下对应的IP一行
文本:
ps -ef |grep ifstat_monitor.sh
root     25356 30188  0 16:42 ?        00:00:00 /bin/bash ./ifstat_monitor.sh
root     25365 25363  0 16:42 ?        00:00:00 bash -c ps -ef |grep ifstat_monitor.sh
root     25367 25365  0 16:42 ?        00:00:00 grep ifstat_monitor.sh
root     30188     1  0 Aug16 ?        00:13:03 /bin/bash ./ifstat_monitor.sh
192.168.158.36  OK

ps -ef |grep ifstat_monitor.sh
root     13375     1  0 Aug16 ?        00:12:57 /bin/bash ./ifstat_monitor.sh
root     23117 13375  0 16:42 ?        00:00:00 /bin/bash ./ifstat_monitor.sh
root     23141 23139  0 16:42 ?        00:00:00 bash -c ps -ef |grep ifstat_monitor.sh
root     23151 23141  0 16:42 ?        00:00:00 grep ifstat_monitor.sh
192.168.158.37  OK

ps -ef |grep ifstat_monitor.sh
root     44449 44447  0 16:42 ?        00:00:00 bash -c ps -ef |grep ifstat_monitor.sh
root     44451 44449  0 16:42 ?        00:00:00 grep ifstat_monitor.sh
192.168.158.39  OK

ps -ef |grep ifstat_monitor.sh
root     31876 42910  0 16:43 ?        00:00:00 /bin/bash ./ifstat_monitor.sh
root     31893 31852  0 16:43 ?        00:00:00 bash -c ps -ef |grep ifstat_monitor.sh
root     31904 31893  0 16:43 ?        00:00:00 grep ifstat_monitor.sh
root     42910     1  0 Aug16 ?        00:12:55 /bin/bash ./ifstat_monitor.sh
192.168.158.161 OK

想得到如下:
192.168.158.36  OK
192.168.158.37  OK
.....
192.168.158.161  OK

我想用命令行的方式处理该问题, 可是结果都比较奇怪. 不知道该如何弄了, 还请大家指点, 谢谢大家...



作者: sunzhiguolu    时间: 2016-11-23 22:33
我的代码如下:
  1. perl -00ne 'print "|||$_"' f
复制代码

我现在别说处理文件了, 现在就是正常显示都成问题了. 还请大家帮忙指点, 谢谢大家...
作者: sunzhiguolu    时间: 2016-11-23 22:48
我其实就是想 按照段落的方式读取文本.
如果满足 /bin/bash ./ifstat_monitor.sh 条件, 那么就打印以 OK 结尾的那一行的数字.
作者: sunzhiguolu    时间: 2016-11-24 10:14
哪位大神有时间帮我看下, 谢谢!
作者: stanley_tam    时间: 2016-11-24 22:38
从不用perl one liner...
作者: sunzhiguolu    时间: 2016-11-24 23:16
回复 5# stanley_tam
大师, 为啥呀?


作者: zhlong8    时间: 2016-11-25 21:24
单行脚本难看难懂,为了短小做了很多假设,很容易出 bug。

不会一行的可以写复杂的先
  1. $/ = "\n\n";

  2. while (<>) {
  3.     if ($_ =~ m</bin/bash \./ifstat_monitor\.sh>) {
  4.         say +(split "\n", $_)[-1];
  5.     }
  6. }
复制代码

作者: sunzhiguolu    时间: 2016-12-27 22:26
回复 7# zhlong8
版主大神,向您请教个问题。
say +(split "\n", $_)[-1];
这个加号起到一个什么作用,能够提高编译器的解释速度吗?



作者: zhlong8    时间: 2016-12-28 10:33
回复 8# sunzhiguolu

say 就是个函数啊,不加+ 括号里面就成 say 的参数了。+ 做前缀操作符不跟数字的话就这一个用处了。

作者: zhlong8    时间: 2016-12-28 10:35
perl 可以不加括号通常代码会比较简洁,而这就是代价




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2