Re: shell script replacing original file
am 31.03.2008 08:32:19 von DFS
Gary Johnson wrote:
>
> Some versions of sed include a -i option that tells sed to edit the
> file in-place.
Out of curiosity, how is the -i option implemented ? Does it
create and then delete temporary file internally ?
Cheers.
Re: shell script replacing original file
am 31.03.2008 09:54:03 von PK
Ming Ching TIew wrote:
> Gary Johnson wrote:
>>
>> Some versions of sed include a -i option that tells sed to edit the
>> file in-place.
>
> Out of curiosity, how is the -i option implemented ? Does it
> create and then delete temporary file internally ?
GNU sed does it this way:
`-i[SUFFIX]'
`--in-place[=SUFFIX]'
This option specifies that files are to be edited in-place. GNU
`sed' does this by creating a temporary file and sending output to
this file rather than to the standard output.(1).
This option implies `-s'.
When the end of the file is reached, the temporary file is renamed
to the output file's original name. The extension, if supplied,
is used to modify the name of the old file before renaming the
temporary file, thereby making a backup copy(2)).
This rule is followed: if the extension doesn't contain a `*',
then it is appended to the end of the current filename as a
suffix; if the extension does contain one or more `*' characters,
then _each_ asterisk is replaced with the current filename. This
allows you to add a prefix to the backup file, instead of (or in
addition to) a suffix, or even to place backup copies of the
original files into another directory (provided the directory
already exists).
If no extension is supplied, the original file is overwritten
without making a backup.
---------- Footnotes ----------
(1) This applies to commands such as `=', `a', `c', `i', `l', `p'.
You can still write to the standard output by using the `w' or `W'
commands together with the `/dev/stdout' special file
(2) Note that GNU `sed' creates the backup file whether or not
any output is actually changed.
--
All the commands are tested with bash and GNU tools, so they may use
nonstandard features. I try to mention when something is nonstandard (if
I'm aware of that), but I may miss something. Corrections are welcome.