smya.dsh
smya.dsh

Reputation: 661

How to append text to a specific lines in a file using shell script?

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?

Upvotes: 3

Views: 14096

Answers (3)

dogbane
dogbane

Reputation: 274838

Use a loop to iterate over the lines in the file and run ps to check if the process if running:

while IFS= read -r line
do
    pid="$(awk '{print $NF}' <<< $line)"
    unset status
    if ps --no-headers -p "$pid" > /dev/null
    then
        status="running"
    fi
    echo "$line $status"
done < file

Upvotes: 2

Vijay
Vijay

Reputation: 67301

awk '$2==3696{$3="running";}1' your_file


>cat temp
foo1 3464 
foo2 3696 
foo3 4562 
> awk '$2==3696{$3="running";}1' temp
foo1 3464 
foo2 3696 running
foo3 4562 
> 

Upvotes: 1

Lev Levitsky
Lev Levitsky

Reputation: 65851

$ sed '/3696/ s/$/running/' file.txt 
foo1 3464 
foo2 3696 running
foo3 4562 

or

$ sed 's/3696/& running/' file.txt 
foo1 3464 
foo2 3696 running 
foo3 4562 

Add the -i option to save the changes back to file.txt.

Upvotes: 11

Related Questions