
[英]How do you copy lines that contain specific strings from a .csv file to a .txt file in Python using %BASH?
[英]Copy a txt file twice to a different file using bash
我试图捕获一个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
所报告的getconf ARG_MAX
- 假设在Linux上限制为2,097,152
字节(2MB),这是不可能的。
您可以使用追加运算符>>
,而不是>
。 然后根据需要调整循环计数以获得所需的输出大小。
您应该调整代码,使其如下所示:
for i in {1..3}; do cat file.txt >> file_new.txt; done
>>
运算符将数据附加到文件而不是写入( >
)
正如其他人所提到的,你可以使用>>
来追加。 但是,你也可以只调用一次cat
并让它读取文件3次。 例如:
n=3; cat $( yes file.txt | sed ${n}q ) > file_new.txt
请注意,此解决方案具有共同的反模式,无法正确引用参数,如果文件名包含空格,则会导致问题。 请参阅mklement的解决方案以获得更强大的解决方案。
如果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
for i in {1..3}; do cat file.txt >> file_new.txt; done
此命令将file_new.txt
(3GB),因为for i in {1..3}
将运行三次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.