Reputation: 1031
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.
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:
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 CMD 1 /sbin/init 2 3 4 5 6 7 8 9 17
Upvotes: 0
Views: 782
Reputation: 160551
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.
It created a file called "proc.2011-04-16" which looks like:
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
Upvotes: 2
Reputation: 168081
Just do
string.gsub(/\[.*?\]/, '')
or
string.gsub(/\[[^\[\]]*\]/, '')
Upvotes: 1