Similar to Jasen's answer, this is a basis for a utility.
The code sponge in package moreutils is designed to allow an in-place capability to almost any program, albeit externally. Essentially it soaks up input from STDIN and then writes the collected output to a filename, but NOT with re-direction.
We liked the idea, so we created a work-alike that collects data in memory, as opposed to a file as the real sponge does.
Here is a snippet of shell script to illustrate this:
# Utility functions: print-as-echo, print-line-with-visual-space.
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
pl " Input files data2, data3:"
head data[23]
pe
ls -gGli data[23]
pl " Results, re-write file from memory, preserving inode:"
cat data[23] | ./absorb-memory-public data3
head -v data3
pe
ls -gGli data3
Producing:
-----
Input files data2, data3:
==> data2 <==
hello world
hello bangladesh
==> data3 <==
Dhaka in Bangladesh
Dhaka is capital of Bangladesh
1051395 -rw-r--r-- 1 30 Jan 7 08:58 data2
1052221 -rw-r--r-- 1 53 Jan 7 08:58 data3
-----
Results, re-write file from memory, preserving inode:
==> data3 <==
hello world
hello bangladesh
Dhaka in Bangladesh
Dhaka is capital of Bangladesh
1052221 -rw-r--r-- 1 83 Jan 7 08:58 data3
The core perl code is quite short (especially without error checking, the addition of which may be desirable):
use warnings;
use strict;
use Carp;
# Avoid hang for argument matching "-version","--version", etc.
exit(0) if @ARGV && $ARGV[0] =~ /-version/;
my ( $file, $f, $memory );
$file = shift || croak("Need a filename.");
$/ = 0777; # Slurp the entire STDIN
$memory = do { local $/; <> };
open( $f, ">", $file ) || die " Cannot open file \"$file\" for write.\n";
print $f "$memory";
Run on a system like:
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution : Debian 8.9 (jessie)
bash GNU bash 4.3.30
perl 5.20.2
Best wishes ... cheers, drl
file2
tofile1
and then move it over the top offile2
. That way you don't create a new file, you just overwrite the old. – Wildcard Jan 03 '18 at 01:57