【发布时间】:2012-06-30 06:58:45
【问题描述】:
如何将 file1.txt 中的数据添加到 file2.txt?
【问题讨论】:
如何将 file1.txt 中的数据添加到 file2.txt?
【问题讨论】:
下面的命令会将这两个文件合并为一个
cat file1.txt file2.txt > file3.txt; mv file3.txt file2.txt
【讨论】:
sed 路线在这里绝对没有意义。
cat file1.txt file2.txt > file2.txt 这样的命令中执行此操作。它将无限循环运行。在我按下 ctrl+C 之前,我有大约 10 秒的时间。 13 行文件和 7 行文件中的 8817181 行。回复者回复的原始评论已被删除,因此不清楚这是一个问题。
写入文件的方式类似于 1)。附加在文件末尾或 2).重写那个文件。
如果你想把file1.txt中的内容放在file2.txt之前,恐怕你需要重写合并后的罚款。
【讨论】:
您可以使用来自moreutils 的sponge 在管道中执行此操作:
cat file1.txt file2.txt | sponge file2.txt
【讨论】:
使用 GNU sed 的另一种方式:
sed -i -e '1rfile1.txt' -e '1{h;d}' -e '2{x;G}' file2.txt
即:
file1.txt的内容
它有点棘手的原因是r 命令附加了内容,
并且第 0 行不可寻址,所以我们必须在第 1 行进行,
将原始行的内容移开,然后在附加文件内容后将其带回。
【讨论】:
file2.txt 包含单行,这将不起作用
如果它在您的系统上可用,那么来自 moreutils 的 sponge 就是为此而设计的。这是一个例子:
cat file1.txt file2.txt | sponge file2.txt
如果您没有sponge,则以下脚本使用临时文件执行相同的工作。它确保其他用户无法访问临时文件,并在最后清理它。
如果您的系统或脚本崩溃,您可能需要手动清理临时文件。在 Bash 4.4.23 和 Debian 10 (Buster) Gnu/Linux 上测试。
#!/bin/bash
#
# ----------------------------------------------------------------------------------------------------------------------
# usage [ from, to ]
# [ from, to ]
# ----------------------------------------------------------------------------------------------------------------------
# Purpose:
# Prepend the contents of file [from], to file [to], leaving the result in file [to].
# ----------------------------------------------------------------------------------------------------------------------
# check
[[ $# -ne 2 ]] && echo "[exit]: two filenames are required" >&2 && exit 1
# init
from="$1"
to="$2"
tmp_fn=$( mktemp -t TEMP_FILE_prepend.XXXXXXXX )
chmod 600 "$tmp_fn"
# prepend
cat "$from" "$to" > "$tmp_fn"
mv "$tmp_fn" "$to"
# cleanup
rm -f "$tmp_fn"
# [End]
【讨论】: