0

I have a text file (file.txt) having content something like:

foo1 3464 
foo2 3696 
foo3 4562 

It contains the process and respective PID.

Using shell script, I want to append a string (running/not running) to that lines in this file, according to the PID.

For example, in the above file, for line containing PID 3696, I want to append a string "running" at the end, so that the file becomes:

foo1 3464 
foo2 3696 running
foo3 4562 

How can i do it?

1 Answer 1

3

With perl, by actually checking if the process is running (Linux only):

perl -ape '$pid = $F[1]; if (-d "/proc/$pid") {s/$/ running/}'

With sed:

sed -i '/\<3696\>/ s/$/ running/' "$file"

With perl:

perl -i -pe 's/$/ running/ if /\b3696\b/' "$file"

perl -i -ape 's/$/ running/ if $F[1] eq "3696"' "$file"

With ed:

ed "$file" <<-EOF
/\<3696\>/ s/$/ running/
wq
EOF

(Here \< \> (sed) and \b \b (perl) mean word boundaries – both examples only match "3696", but not "136960" or such.)

1
  • If i want to append the text according to the line no then what will be the command?
    – smya.dsh
    Dec 27, 2012 at 10:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .