linux - 使用 bash 将一个 txt 文件复制两次到另一个文件

标签 linux bash shell

我正在尝试 cat 一个 file.txt 并在整个内容中循环两次并将其复制到新文件 file_new.txt。我使用的 bash 命令如下:

for i in {1..3}; do cat file.txt > file_new.txt; done

上面的命令只是给我与 file.txt 相同的文件内容。因此 file_new.txt 的大小也是相同的 (1 GB)。

基本上,如果 file.txt 是一个 1GB 的文件,那么我希望 file_new.txt 是一个 2GB 的文件,将 file.txt 的内容加倍。拜托,有人可以帮忙吗?谢谢。

最佳答案

简单地将重定向应用到 for 循环作为一个整体:

for i in {1..3}; do cat file.txt; done > file_new.txt

与使用 >>> 相比的优势(除了不必多次打开和关闭文件外)是您无需确保首先截断预先存在的输出文件。


请注意,此方法的概括使用组命令({ ...; ...; }) 将重定向应用于多个命令;例如:

$ { echo hi; echo there; } > out.txt; cat out.txt
hi
there

考虑到正在输出整个文件,每次重复调用 cat 的成本可能无关紧要,但这里有一个调用 cat 的稳健方法> 只有一次:[1]

# Create an array of repetitions of filename 'file' as needed.
files=(); for ((i=0; i<3; ++i)); do files[i]='file'; done
# Pass all repetitions *at once* as arguments to `cat`.
cat "${files[@]}" > file_new.txt

[1] 请注意,假设您可能会遇到平台的命令行长度限制,如 getconf ARG_MAX 所报告 - 假定在 Linux 上该限制为 2,097,152 字节 (2MB),但这不太可能。

关于linux - 使用 bash 将一个 txt 文件复制两次到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43508319/

相关文章:

C函数判断IP地址是否为多播地址

linux - Subversion 提交/USVN/Raspberry Pi 上的 500 内部服务器错误

linux - 根据文件数量压缩文件夹中的一组日志文件

shell - 如何恢复这个 1mb 的 sql 转储?

linux - 如何在ubuntu中/opt目录下运行和安装文件?

c - FTP服务器返回码: How to connect with a host using my own TCP server and Linux built-in client

linux - sed 用文字替换换行符和文字?

BASH 脚本 : when to include the back slash symbol

linux - 比较 2 个文件并仅删除重复行一次

linux sftp :file transfer error