Linux Add text at specific line number in a file

We can add some text at a specific line number in a file using a simple sed expression.

Example:

$ sed "3n some text here" inputFile.txt

Above example will add “some text here” string in inputFile.txt by adding new line.

Lets consider I have a text file t.txt with content as follows:

$ cat t.txt

1

2

3

In t.txt file I would like to add “hello” at line 3, it should done as follows.

$ sed "3i hello" t.txt

Output:

1
2
hello
3

If you use -i option with sed, it will edit file in place without printing it to screen.

Ex: $ sed -i "3i hello" t.txt

This example shouldn’t print any text on your screen, and your input text file will update automatically.

Now run cat command on your input text and check for your modification, it should be updated.

In our case run cat on t.txt

$ cat t.txt

Output:

1
2
hello
3

-Sany

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s