2

I am trying to write a command output to a csv file .Below is the command i want to use to write the data into a csv file

ps -eo pid,comm,pmem,vsz | grep process  | awk '{print $1",",$2",",$3",",$4}'

How we can do this in Perl . Header of the csv file should have and then corresponding values for this :

pid,comm,pmem,vsz

I was trying to do something like this but it is not working for me :

echo "execution started.."

pid,comm,pmem,vsz >> out.txt

while [ true ]; do
    echo "running.."
    sleep 2
    ps -eo pid,comm,pmem,vsz | grep process  | awk '{print $1",",$2",",$3",",$4}' >> out.txt
done
Developer
  • 6,292
  • 19
  • 55
  • 115
  • Remember that the CSV format requires escaping any quotes that might appear in your data. – tadman Aug 30 '18 at 21:47
  • 2
    For Perl solutions see [this answer](https://stackoverflow.com/questions/1444096/how-do-i-create-a-csv-file-using-perl). – tadman Aug 30 '18 at 21:48
  • 1
    Which part of this are you having trouble with? The `ps` part, the `grep` part, or the `awk` part? Are you trying to do all of this in Perl without calling `ps`? – melpomene Aug 30 '18 at 23:27
  • 2
    What exactly do you mean by "is not working"? Please provide a [mcve]. Also, none of your code uses Perl, so how is this related to your question? – melpomene Aug 30 '18 at 23:29

2 Answers2

1

The link in the comment by tadman has a lot of information, but you can also do

ps -eo pid,comm,pmem,vsz | grep process_name | 
    perl -nE '
        BEGIN { say "pid,comm,pmem,vsz" }; 
        say join ",", split
    ' > ps_process.out

(broken into multiple lines for readability)

The BEGIN block is executed only in the compilation phase so it's not repeated in iterations.

zdim
  • 64,580
  • 5
  • 52
  • 81
0

Here is a straightforward way, using the -a switch to implicity create @F for each line piped in (it's a shortcut for saying @F = split /\s+\, $_)

echo pid,comm,pmem,vsz > out.csv
ps -eo pid,comm,pmem,vsz | perl -lnaE 'say join ",", @F' >> out.csv
beasy
  • 1,227
  • 8
  • 16