Skip to content
Advertisement

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?

Advertisement

Answer

$ 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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement