S Andrew
S Andrew

Reputation: 7198

How to insert a line in file in linux

I need to insert a line at line number 3 in file.txt. For this I am using sed. I need to insert below text in file:

Location=\home\user\Files\myfile.txt

To insert above line, I am doing:

sudo sed -i '3iLocation=\home\user\Files\myfile.txt' file.txt

This command is running but the text inserted is :

Location=homeuserFilesmyfile.txt

Why is this happening. How can I also include \.

Thanks

Upvotes: 1

Views: 95

Answers (2)

Sanket Parmar
Sanket Parmar

Reputation: 1577

Use escape character '\'.

sed -i '3iLocation=\home\user\Files\roamingfile.txt' file.txt

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

You need to escape a backslash \ to interpret it literally.

To append the line without linebreak:

sed -i '3 s/$/Location=\\home\\user\\Files\\myfile.txt/' file.txt
  • $ - regex anchor, points to the end of the string

To insert specific line before the 3rd line:

sed -i '3iLocation=\\home\\user\\Files\\myfile.txt/' file.txt

Upvotes: 2

Related Questions