Burak
Burak

Reputation: 5764

How can I insert a line with a new line appended to a file using sed on mac?

I want to insert a text line, lets say "hello" to the 3rd line of the file. And there should be a new line appended:

1st
2nd
Hello

3rd

How can I do that?

Upvotes: 1

Views: 132

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '3 i\
Hello\
' YopurFile

Insert following line (preceded by \) at line 3

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77075

Very straightforward with awk:

$ cat file
1
2
3
4
5
6

$ awk 'NR==3{print "hello\n"}1' file
1
2
hello

3
4
5
6

Where NR is the line number. You can set it to any number you wish to insert text to.

Upvotes: 2

John1024
John1024

Reputation: 113814

$ sed '3s/^/Hello\n\n/' file.txt
1st
2nd
Hello

3rd

The 3 at the beginning of the sed command specifies that the command should be applied to line 3 only. Thus, the command, 3s/^/Hello\n\n/, substitutes in "Hello" and two new lines to the beginning (^ matches the beginning of a line) of line 3. Otherwise, the file is left unchanged.

Upvotes: 1

Daniel
Daniel

Reputation: 4539

Does it have to be sed?

head -2 infile ; echo Hello ; echo ; tail +3 infile

Upvotes: 1

Related Questions