help-bash
[Top][All Lists]
Advanced

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

Re: Write to file at specific location


From: Seth David Schoen
Subject: Re: Write to file at specific location
Date: Mon, 5 Jul 2021 15:09:52 -0700

Julius Hamilton writes:

> Hey,
> 
> I would like to schedule a command to execute at a certain time. When it
> does, it should write its output to a specific place in a text file. The
> contents of the file might shift around a bit in the intervening time. So I
> was thinking the best way would be to put some highly unique symbol in the
> place it should be written, as an identifier. In a Vim plug-in I saw once,
> I am pretty sure it used very unique symbols as tokens inserted into the
> text (for a different purpose). Would this be a standard method to flag a
> location in a file? How does one specify the symbol? Perhaps by a unicode
> U+387 style code?

Unix and bash don't really have a "file insert" feature natively (to
add data in the middle of a file without overwriting the data that
comes later in the file).  The most common way to do this is to
rewrite the original remainder of the file afterward, which can be a
lot of extra memory and disk utilization for a large file.

You could consider using sed -i, which behind the scenes is actually
using a temporary file with a copy of the original, though to you as
the user feels like it's "editing in place".  It is meant to work on
text files.

For example

sed -i "/sentinel/aAdditional text" somefile.txt

would add a new line consisting of "Additional text" right after every
line containing the string "sentinel" in somefile.txt.

For this method, newlines have to be represented as \n, so you couldn't
use it directly with multiline output from a script.  You could send
the script to a temporary file and then use some command to print the
lines up to the sentinel, then print your output from the temporary
file, then print the rest of the lines from the text file.

-- 
Seth David Schoen <schoen@loyalty.org>      |  Qué empresa fácil no pensar
     http://www.loyalty.org/~schoen/        |  en un tigre, reflexioné.
                                            |        -- Borges, "El Zahir"



reply via email to

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