DD1
DD1

Reputation: 367

Inserting spaces before the word while adding lines using sed

My file content-

abc
def

I want to add two lines after abc with spaces before it

My final file content should be -

abc
    123
def

I am using the below command, but not working for me, plz help me

sudo sed -i "/abc/a\\\123" file.txt

Note - There is no space between lines, I just want to put some spaces before the new line (i.e. before the line 123)

Upvotes: 5

Views: 5712

Answers (3)

Ed Morton
Ed Morton

Reputation: 204638

Just use awk for clarity, portability, etc.:

awk '{print} /abc/{print "    123"}' file

Upvotes: 0

sat
sat

Reputation: 14979

You can use this sed:

sed -i '/abc/a\    123' file

Ex:

$ sed '/abc/a\    123' file
abc
    123
def

Upvotes: 10

P....
P....

Reputation: 18411

Following is awk solution ,if you are open for awk.

Sample input:

cat infile
abc
def

Explanation:

Check for pattern abc if found, update the current line with current line followed by newline followed by 123. And 1 invokes awk's default action of printing.

note : Newline is printed using awk's inbuilt variable called ORS ,which is default set to newline.

awk '/abc/ {$0=$0 ORS "    123" }1' infile
abc
    123
def

To make changes in orignal file:

awk '/abc/ {$0=$0 ORS "    123" }1' infile >infile.tmp && mv infile.tmp infile

Upvotes: 1

Related Questions