Inserting text in a file

August 2017

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.


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:
  • With numbering

sed "16iNotes : The denial achieved with an exclamation point! n " file.txt
  • With parameters



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:
  • With numbering


sed "8a \"ed\"is a text editor making use of oriented line. It is useto createAmend or otherwise manipulate text files."file.txt
  • With parameters


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:
  • With numbering

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
  • With parameters


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

Related


Published by jak58. Latest update on February 5, 2012 at 07:47 PM by Paul Berentzen.
This document, titled "Inserting text in a file," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).