连接多个文件的好方法是什么,但删除标题行(事先未知的标题行数),并将第一个文件标题行保留为新连接文件中的标题?
我想在python中这样做,但只要我可以使用subprocess来调用unix命令,awk或其他语言也会工作.
注意:标题行都以#开头.
我会这样做;
(cat file1; sed '/^#/d' file2 file3 file4) > newFile
Run Code Online (Sandbox Code Playgroud)
使用 Python 是这样的:
files = ["file1","file2","file3"]
with open("output_file","w") as outfile:
with open(files[0]) as f1:
for line in f1: #keep the header from file1
outfile.write(line)
for x in files[1:]:
with open(x) as f1:
for line in f1:
if not line.startswith("#"):
outfile.write(line)
Run Code Online (Sandbox Code Playgroud)
您还可以fileinput在此处使用该模块:
该模块实现了一个辅助类和函数来快速编写标准输入或文件列表的循环。
import fileinput
header_over = False
with open("out_file","w") as outfile:
for line in fileinput.input():
if line.startswith("#") and not header_over:
outfile.write(line)
elif not line.startswith("#"):
outfile.write(line)
header_over = True
Run Code Online (Sandbox Code Playgroud)
用法 :$ python so.py file1 file2 file3
输入:
文件1:
#header file1
foo
bar
Run Code Online (Sandbox Code Playgroud)
文件2:
#header file2
spam
eggs
Run Code Online (Sandbox Code Playgroud)
文件3:
#header file3
python
file
Run Code Online (Sandbox Code Playgroud)
输出:
#header file1
foo
bar
spam
eggs
python
file
Run Code Online (Sandbox Code Playgroud)