sed is a powerful tool to edit files line by line. However, when you try to
manipulate more than one line at a time, it becomes more difficult to create
The point of this article is to find a pattern in a file and, when this pattern is found, add a new line just below.
The use case
Imagine that we have a lot of AsciiDoc documents. These articles have metadata at the beginning. However, the language is not defined, in any article. We want to add a metadata to define the lang of all articles (we know they all are in english).
For example, this is the metadata of this article
= Using `sed` to add new lines :author: woshilapin :email: firstname.lastname@example.org :date: 30-11-2013 :slug: using-sed-to-add-new-lines :category: tech :tags: sed
We want to add the
:lang: metadata after the
sed command, we will use the
a\ function to add a new line after
the pattern we are looking for.
$ sed '/:date:/ a\ :lang: en\ ' on-fichier.asciidoc
Notice that there is two new lines. The first says
add a new line after the
pattern you’re looking for'' and the second says add a new line at the end of
the line I’m creating”. You may use the
-i option of
sed to replace in the
file (the default is to print on the standard output).