To meet
programming needs, one may need to
insert text in a text file at designated areas. Linux has SED
, the utility which allows the programmer to achieve this by following the SED
syntax. This enables the user to insert, add or replace text in a document. The
script is written in such a way that one needs to point out the specific area of a line, or the line, where the addition/insertion or the replacement needs to happen.
Inserting the text in a file has now become easy.
Inserting text in a file
Introduction
It is sometimes useful to insert text into the header of one or more documents, or in a specific part of the document (before or after a specific line).
Here is how to use SED to achieve this.
Syntax
Whatever the method (insertion, addition or exchange), the syntax will remain 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 point at which a new line should be inserted by using its corresponding number or a pattern.
Example:
sed "16iNotes : The denial achieved with an exclamation point! n " file.txt
sed "/Conclusion/iNotes: 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 a new line is to be inserted by using its corresponding number or a pattern.
Example:
sed "8a \"ed\"is a text editor making use of oriented line. It is useto createAmend or otherwise manipulate text files."file.txt
sed "/\"ed\"/a \"ed\"is a text editor making use of oriented line. It is useto createAmend 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 the new one, either using 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
See also
Knowledge communities.
Published by
jak58 -
Latest update by Paul Berentzen