Re: how to: remove last line from file 1 and append t0 file 2

From: Janis Papanagnou (Janis_Papanagnou_at_hotmail.com)
Date: 07/08/05


Date: Fri, 08 Jul 2005 01:13:59 +0200

John DuBois wrote:
> In article <LIbze.3348$p%3.21352@typhoon.sonic.net>,
> Icarus Sparry <usenet@icarus.freeuk.com> wrote:
>
>>On Thu, 07 Jul 2005 16:26:24 +0200, Anna Lauer wrote:
>>
>>>subject says it all. how do i remove the last line from "file1" and
>>>append it to file2?
>>>
>>>my solution: use tail -1 and sed '$d' to get/remove the last line.
>>>
>>>because file1 is quite huge i do not want to make a copy of file1.
>>>how do i remove the last line without having to make a copy?
>>
>>If your system supports it (and modern ones do), write a special program
>>which invokes the 'truncate' or 'ftruncate' system calls. I am not aware
>>of any standard program that will do this for you.
>
>
> Modern versions of dd will truncate files. To remove the end of a file,
> first find the offset at which you want to truncate. In this case you would
> use tail -1 to get the last line and subtract its length (including its
> terminal newline) from the size of the file. If that gives a result of zero,
> trucate the file with '>'. Otherwise, get the character immediately before
> that position. In this case that would be a newline. Echo the character into
> dd with a seek position immediately before the offset at which you want to
> truncate:
>
> echo "" | dd of=yourfile oseek=offset-minus-1 bs=1
>
> John

Alternatively remove the last line using (GNU) grep's offset information...

   grep -b "" yourfile

The complete command to remove the last line is, e.g.

   echo "" | dd of=yourfile bs=1 seek=$(
                         grep -b "" yourfile | awk -F: 'END{print $1 - 1}' )

Janis



Relevant Pages