将多行文本文档合并为一个
Combine multiple lines of text documents into one
我有数千个文本文档,它们的文本行数各不相同。我想将每个文档中的所有行单独组合成一行。例如:
abcd
efgh
ijkl
应该变成
abcd efgh ijkl
我尝试使用 sed 命令,但由于每个文档中的行数不同,它完全没有达到我想要的效果。请建议我能做什么。我正在 ubuntu 中处理 python。一行命令会有很大帮助。提前致谢!
没有必要使用 python。这就是诀窍:
% echo `cat input.txt` > output.txt
要应用于一堆文件,您可以使用循环。例如。如果您使用 bash
:
for inputfile in /path/to/directory/with/files/* ; do
echo `cat ${inputfile}` > ${inputfile}2
done
如果您将脚本放在与文件相同的目录中,则以下代码应该有效。
import os
count = 0
for doc in os.listdir('C:\Users\B\Desktop\newdocs'):
if doc.endswith(".txt"):
with open(doc, 'r') as f:
single_line = ''.join([line for line in f])
single_space = ' '.join(single_line.split())
with open("new_doc{}.txt".format(count) , "w") as doc:
doc.write(single_space)
count += 1
else:
continue
@inspectorG4dget 的代码比我的更紧凑——因此我认为它更好。我试图让我的尽可能对用户友好。希望对您有所帮助!
假设您所有的文件都在一个目录中,具有 .txt 扩展名,并且您可以使用 bash 访问 linux 框,您可以像这样使用 tr:
for i in *.txt ; do tr '\n' ' ' < $i > $i.one; done
对于每个 "file.txt",这将生成一个 "file.txt.one",所有文本都在一行中。
如果你想要一个直接对文件进行操作的解决方案,你可以使用 gnu sed(注意这会破坏你的起始文件 - 在尝试之前备份目录):
sed -i -n 'H;${x;s|\n| |g;p};' *.txt
如果您的文件不在同一目录中,您可以使用带 -exec 的查找:
find . -name "*.txt" -exec YOUR_COMMAND \{\} \;
如果这不起作用,也许有关您尝试执行的操作的更多详细信息会有所帮助。
我有数千个文本文档,它们的文本行数各不相同。我想将每个文档中的所有行单独组合成一行。例如:
abcd
efgh
ijkl
应该变成
abcd efgh ijkl
我尝试使用 sed 命令,但由于每个文档中的行数不同,它完全没有达到我想要的效果。请建议我能做什么。我正在 ubuntu 中处理 python。一行命令会有很大帮助。提前致谢!
没有必要使用 python。这就是诀窍:
% echo `cat input.txt` > output.txt
要应用于一堆文件,您可以使用循环。例如。如果您使用 bash
:
for inputfile in /path/to/directory/with/files/* ; do
echo `cat ${inputfile}` > ${inputfile}2
done
如果您将脚本放在与文件相同的目录中,则以下代码应该有效。
import os
count = 0
for doc in os.listdir('C:\Users\B\Desktop\newdocs'):
if doc.endswith(".txt"):
with open(doc, 'r') as f:
single_line = ''.join([line for line in f])
single_space = ' '.join(single_line.split())
with open("new_doc{}.txt".format(count) , "w") as doc:
doc.write(single_space)
count += 1
else:
continue
@inspectorG4dget 的代码比我的更紧凑——因此我认为它更好。我试图让我的尽可能对用户友好。希望对您有所帮助!
假设您所有的文件都在一个目录中,具有 .txt 扩展名,并且您可以使用 bash 访问 linux 框,您可以像这样使用 tr:
for i in *.txt ; do tr '\n' ' ' < $i > $i.one; done
对于每个 "file.txt",这将生成一个 "file.txt.one",所有文本都在一行中。
如果你想要一个直接对文件进行操作的解决方案,你可以使用 gnu sed(注意这会破坏你的起始文件 - 在尝试之前备份目录):
sed -i -n 'H;${x;s|\n| |g;p};' *.txt
如果您的文件不在同一目录中,您可以使用带 -exec 的查找:
find . -name "*.txt" -exec YOUR_COMMAND \{\} \;
如果这不起作用,也许有关您尝试执行的操作的更多详细信息会有所帮助。