Inserting text in a file
Introduction
It is sometimes useful to insert text in the header of one or more document (s) or in a specific part of the document (before or after a specific line).
The publisher of flux "sed" can help us in this task and we will see how.
Syntax
Whatever the method (insertion, addition or exchange), the syntax will remains the same:
sed '{/pattern/|/regexp/|n}{i|a|c}\<text to be iserted>' file
There are three ways to insert text into a document:
- insert beforehand (with the "i" as integration)
- add after (with the "a" parameter as after)
- replacement (with the "c" for change)
Insert a line with "i"
The syntax is very simple, simply designate the front line which must be inserted a new line or by its corresponding number, or a pattern.
Example:
sed "16i\Notes : The denial achieved with an exclamation point! \n " file.txt
sed "/Conclusion/i\Notes: negation achieved with an exclamation point ! \n" file.txt
Adding a line with "a"
The syntax is as simple, simply designate the line after which must be inserted a new line or by its corresponding number, or a pattern.
Example:
sed "8a \"ed\"is a text editor making use of oriented line. It is useto create\Amend or otherwise manipulate text files."file.txt
sed "/\"ed\"/a \"ed\"is a text editor making use of oriented line. It is useto create\Amend or otherwise manipulate text files."file.txt
Changing a line with "c"
The syntax remains the same, simply designate the line to be replaced by our new line, either by its corresponding number, or a pattern.
Example:
sed "/14/c Various parameters can be passed at the end of expression, such as the \"g\"(for global), for a total replacement of each case" file.txt
sed "/global/c Various parameters can be passed at the end of expression, such as the \"g\"(for global), for a total replacement of each case" file.txt