[英]Replace strings in a file with ruby
I'm trying to create a program that reads ps
and outputs the pid
and commandline
, but if the process was started by the kernel it should return a blank line. 我正在尝试创建一个读取
ps
并输出pid
和commandline
,但是如果该进程是由内核启动的,则应返回一个空行。
require 'fileutils'
procs=`ps -eo pid,cmd`
o = File.open("proc","w")
f = o.write("proc")
o.close
f_in = File.open('proc', 'r')
f_out = File.open('procs', 'w')
replace = ""
f_in.each do |line|
if line =~ (/\s*\[(\w+)\]\$/)
f_out << "\n"
else
f_out << line
end
end
f_out.write("procs")
f_in.close
f_out.close
FileUtils.mv "procs", ["proc", Time.now.strftime("%Y-%m-%d")].join(".")
ps -eo pid,cmd like: ps -eo pid,cmd如:
PID CMD 1 /sbin/init 2 [migration/0] 3 [ksoftirqd/0] 4 [watchdog/0] 5 [events/0] 6 [khelper] 7 [kthread] 8 [xenwatch] 9 [xenbus] 17 [kblockd/0]
I want to remove all of the lines in brackets but keep the PID like this: 我想删除括号中的所有行,但保持PID像这样:
PID CMD 1 /sbin/init 2 3 4 5 6 7 8 9 17
This looks like it will do it: 看起来它将做到:
File.open("proc.#{ Time.now.strftime('%F') }", 'w') do |fo|
fo.puts `ps -eo pid,cmd`.lines.map{ |li| li[ /^([^\[]+)/, 1] }
end
li[ /^([^\\[]+)/, 1]
means "capture everything from the start of the line that isn't a ' [
' and return it. li[ /^([^\\[]+)/, 1]
意思是“从行首捕获不是' [
'的所有内容,然后将其返回。
It created a file called "proc.2011-04-16" which looks like: 它创建了一个名为“ proc.2011-04-16”的文件,如下所示:
PID CMD 1 /sbin/init 2 3 4 5 [...] 255 upstart-udev-bridge --daemon 296 rsyslogd -c4 303 dbus-daemon --system --fork 315 udevd --daemon 398 avahi-daemon: running 443 avahi-daemon: chroot helper 493 [...]
EDIT: There were a couple things I thought could be more succinct: 编辑:我认为有几件事可能更简洁:
File.open('proc.' + Date.today.strftime, 'w') do |fo|
fo.puts `ps -eo pid,cmd`.gsub( /\s+\[.+?\]$/, '')
end
Just do 做就是了
string.gsub(/\[.*?\]/, '')
or 要么
string.gsub(/\[[^\[\]]*\]/, '')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.