我们有时使用一种解决方案来写入与读取的文件相同的文件。以下是手册页的节选:
sponge reads standard input and writes it out to the specified file.
Unlike a shell redirect, sponge soaks up all its input before opening
the output file. This allows constructing pipelines that read from and
write to the same file.
It also creates the output file atomically by renaming a temp file into
place, and preserves the permissions of the output file if it already
exists. If the output file is a special file or symlink, the data will
be written to it.
这是一个片段,表明它可以保留符号链接,尽管我通常使用它来保留inode:
# Utility functions: print-as-echo, print-line-with-visual-space.
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
rm -f pet pet_link
echo "cat" > pet
pl " Input data file $FILE:"
head -v pet
pl " Results, before sed:"
ln --symbolic pet pet_link
ls -ligG pet pet_link
# sed --in-place --follow-symlinks 's/cat/dog/' pet_link
pe
pe " Results, after sed:"
sed 's/cat/dog/' pet_link | sponge pet_link
head -v pet
ls -ligG pet pet_link
产生:
-----
Input data file data1:
==> pet <==
cat
-----
Results, before sed:
1571283 -rw-r--r-- 1 4 Nov 26 23:03 pet
1571286 lrwxrwxrwx 1 3 Nov 26 23:03 pet_link -> pet
Results, after sed:
==> pet <==
cat
1571283 -rw-r--r-- 1 4 Nov 26 23:03 pet
1571286 lrwxrwxrwx 1 3 Nov 26 23:03 pet_link -> pet
在像这样的系统上:
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution : Debian 8.9 (jessie)
bash GNU bash 4.3.30
海绵代码可在moreutils软件包中找到 -一些详细信息:
sponge soak up standard input and write to a file (man)
Path : /usr/bin/sponge
Package : moreutils
Home : http://kitenet.net/~joey/code/moreutils/
Version : 0.52
Type : ELF 64-bit LSB executable, x86-64, version 1 (SYS ...)
在我们的商店中,我们为大型文件编写了一个版本,该版本可写入临时文件。
该软件包可用于Debian,Fedora,macOS(通过brew)等。