sed-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Usage explanation request


From: Assaf Gordon
Subject: Re: Usage explanation request
Date: Sun, 2 Oct 2016 13:33:21 -0400

Hello,

> On Oct 2, 2016, at 04:28, Vagelis Prokopiou <address@hidden> wrote:
> 
> I have seen online the following usage of sed:
> sed  '$iNew Line!' example.file.txt
> 
> This command, inserts the text "New Line!", in a new line, just before the 
> last line of the file.
> 
> I am trying to find this usage in the manual, but I cannot.
> 
> The only "i" options I find, are the "inline" editing, and the "case 
> insensitive" regex search.
> 
> Can anybody clarify this usage?

There are three topics here:

1.
The '$' is an address, referring to the last line of the last input. It is 
explained here:
   https://www.gnu.org/software/sed/manual/html_node/Addresses.html#Addresses

2.
The 'i' is the insert command, explained here:
   
https://www.gnu.org/software/sed/manual/html_node/Other-Commands.html#Other-Commands

3.
The usage that you have shown is a GNU extension, which is perhaps not well 
documented currently.
The GNU sed manual and The POSIX standard for sed ( 
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html )
offers the following syntax:

    i\
    text

for example:

    $ seq 5 | sed '$i\
    New Line!
    '
    
Which will result in:

    1
    2
    3 
    4
    New Line!
    5

That is, the 'i' command must be followed by a backslash, and the line(s) you 
wish to add appear by themselves.

GNU sed, as an extension, accepts text immediately following the 'i':

    $ seq 5 | sed '$iNew Line!'

Additionally, GNU sed will also accept the text as a second program, like so:

    $ seq 5 | sed -e '$i\' -e 'New Line!'

This is useful if you want to add text from a shell variable, e.g.

    $ seq 5 | sed -e '$i\' -e "$VAR"

Note that these are GNU extensions, and are not portable across all systems.
However, they are very likely to be supported on most GNU/Linux systems 
(busybox's sed also supports this syntax).
But 'sed' on Mac OS X complains with:

    $ seq 5 | sed '$iNew Line!'
   sed: 1: "$iNew Line!": command i expects \ followed by text

If you need to write portable scripts, consider using the standard 'i\' syntax 
instead of the extension syntax.

regards,
 - assaf




reply via email to

[Prev in Thread] Current Thread [Next in Thread]