John
John

Reputation: 39

sed to find the first empty line after match and replace

I'm trying to find the first empty line after a match and replace it with my text. For example, if the pattern was Authors:

Authors
-----
author1
author2
author3
...
authorN

-----

I would want sed to append an additional author and a new line:

Authors
-----
author1
author2
author3
...
authorN
authorAdded

-----

These patterns are variable length and location across the file database.

Upvotes: 3

Views: 2343

Answers (2)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed '/^Authors/!b;:a;n;/./ba;inew author' file

Print lines other those that begin with Authors as usual. Then print non-empty lines as usual and on the first empty line insert the required string. N.B. the empty line will also be printed

Upvotes: 6

Jack
Jack

Reputation: 6158

I think awk is your best bet here:

$ cat test.txt
Count
-----
1
2
3
4
5

-----

$ awk '{ if ($1=="") { print last+1; last=last+1; print ""; } else { print; last=$1 } }' test.txt 
Count
-----
1
2
3
4
5
6

-----

Upvotes: 0

Related Questions