smya.dsh
smya.dsh

Reputation: 661

unable to insert text at a particular line of a file using linux sed

I want to replace the 2nd line of a file using linux sed using these following commands.

sed -i"" '2d' /usr/local/services/status.sh
sed -i '2i\testing' /usr/local/services/status.sh

Is there any error in my command? I can't find out. Is there any other way to do it?

Any kind of help is appreciated.

Upvotes: 0

Views: 987

Answers (2)

Guru
Guru

Reputation: 16974

To replace 2nd line:

$ cat file
AIX
Unix
Linux
$ sed -i '2s/.*/testing/' file
$ cat file
AIX
testing
Linux

To insert before the 2nd line:

$ sed -i '2i testing' file

To use a variable as part of subtitution:

$ PID=2456
$ sed -i "2s/.*/testing $PID/" file

Upvotes: 0

potong
potong

Reputation: 58391

This might work for you:

sed -i '2c\testing' file

Upvotes: 1

Related Questions