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

时间:2017-04-20 00:39:17

标签: linux bash shell

我正在尝试捕获一个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的两倍。拜托,有人可以帮忙吗?谢谢。

5 个答案:

答案 0 :(得分:4)

只需将重定向应用于for循环整体

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

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

请注意,此方法的概括使用组命令{ ...; ...; })将重定向应用于命令; e.g:

$ { 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) )但这不太可能。

答案 1 :(得分:3)

您可以使用追加运算符>>,而不是>。然后根据需要调整循环计数以获得所需的输出大小。

答案 2 :(得分:0)

您应该调整代码,使其如下所示:

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

>>运算符将数据附加到文件而不是将其写入(>

答案 3 :(得分:0)

正如其他人所提到的,您可以使用#!/bin/bash # # Filename: rename.sh # Description: Renames files and folders to lowercase recursively # from the current directory # Variables: Source = x # Destination = y # # Rename all directories. This will need to be done first. # # Process each directory’s contents before the directory itself for x in `find * -depth -type d`; do # Translate Caps to Small letters y=$(echo $x | tr '[A-Z]' '[a-z]'); # check if directory exits if [ ! -d $y ]; then mkdir -p $y; fi # check if the source and destination is the same if [ "$x" != "$y" ]; then # check if there are files in the directory # before moving it if [ $(ls "$x") ]; then mv $x/* $y; fi rmdir $x; fi done # # Rename all files # for x in `find * -type f`; do # Translate Caps to Small letters y=$(echo $x | tr '[A-Z]' '[a-z]'); if [ "$x" != "$y" ]; then mv $x $y; fi done exit 0 进行追加。但是,您也可以只调用>>一次并让它读取文件3次。例如:

cat

请注意,此解决方案具有通用的反模式,无法正确引用参数,如果文件名包含空格,则会导致问题。请参阅mklement的解决方案以获得更强大的解决方案。

答案 4 :(得分:0)

如果file.txt是1GB文件, cat file.txt > file_new.txt cat file.txt >> file_new.txt >运算符将创建file_new.txt(1GB),
>>运算符将追加file_new.txt(2GB)。

for i in {1..3}; do cat file.txt >> file_new.txt; done 此命令将生成file_new.txt(3GB),因为for i in {1..3}将运行三次。