Ask a question »

Inserting text in a file

August 2015

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:
  • 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
For unlimited offline reading, you can download this article for free in PDF format:
Inserting-text-in-a-file.pdf

See also

In the same category

Published by jak58. - Latest update by Paul Berentzen
This document entitled « Inserting text in a file » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.