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
4
  • Remember that the CSV format requires escaping any quotes that might appear in your data. Commented Aug 30, 2018 at 21:47
  • 2
    For Perl solutions see this answer. Commented Aug 30, 2018 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? Commented Aug 30, 2018 at 23:27
  • 2
    What exactly do you mean by "is not working"? Please provide a minimal reproducible example. Also, none of your code uses Perl, so how is this related to your question? Commented Aug 30, 2018 at 23:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.