How to append text to a specific lines in a file using shell script?
5,169
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.)
Related videos on Youtube
Author by
smya.dsh
Updated on September 18, 2022Comments
-
smya.dsh over 1 year
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?