# How to replace replace 1 line with 2 lines using sed?



## mrjayviper (Sep 7, 2017)

I have a very simple text file here with the following contents


```
line1
    line2
    line3
    line4
```

I want to modify the contents via sed(or some other app) so it becomes


```
line1
    line2
    #this line was added by sed
    line3
    line4
```

So I tried

sed -e "s/line2/line2\\n#this line was added by sed/" my-text-file-here.txt

but the output is


```
line1
    line2\n#this line was added by sed
    line3
    line4
```

Any ideas on how to do it correctly? I'm using default shell. Thank you


----------



## Jov (Sep 7, 2017)

sed -e '/line2/a\
#this line was added by sed'


----------



## mrjayviper (Sep 7, 2017)

getting an error


----------



## Jov (Sep 7, 2017)

I test it on bash, works fine.

For tcsh, you may use sed script instead of command line.


----------



## Kiiski (Sep 8, 2017)

With `printf` and `ed` you can do


```
printf "%s\n" l 3 i "#this line was added by ed" . w | ed my-text-file-here.txt
```

But added text will be little different of course


----------



## Kiiski (Sep 9, 2017)

After good night sleep I noticed there is also a way to do this with `sed`

```
sed -i '.bak' 's:line2:line2\\
#this line was added by sed:' my-text-file-here.txt
```
By the way, good tutorial about `sed`:
http://www.grymoire.com/Unix/Sed.html


----------



## topcat (Sep 9, 2017)

```
$ sed -e 's/\(line2\)/\1\
> #this line was added by sed/' file_with_lines
line1
line2
#this line was added by sed
line3
line4
```


----------

