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?


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/

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.