我有一个以下格式的文本文件:
Run#1 Step#1 > Connecting to server
Run#1 Step#2 > Connected OK
Run#1 Step#3 > Sending request: {
"path": "/testpage",
"time": "2015-06-07T00:00:00.000Z"
}
Run#1 Step#4 > Request sent OK
我需要做的是处理这个文件。如果每个步骤都打印在一个单独的行上会更容易:
Run#1 Step#1 > Connecting to server
Run#1 Step#2 > Connected OK
Run#1 Step#3 > Sending request: { "path": "/testpage", "time": "2015-06-07T00:00:00.000Z" }
Run#1 Step#4 > Request sent OK
我该怎么做(在bash或ruby / python / ...脚本中)?
答案 0 :(得分:1)
gnu sed solution
cat file | sed ':a; N; $! ba; s/\n//g; s/Run#/\nRun#/g;' | sed '1d;' > outputfile
答案 1 :(得分:1)
使用python对基于以Run#
开头的行的行进行分组,并将不以Run#开头的行的任何部分连接到上一个Run#行,无论内容如何,它也将替换原始文件,您不需要将整个文件读入内存:
from itertools import groupby
from tempfile import NamedTemporaryFile
from shutil import move
with open("file.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
grouped = groupby(f, key=lambda x: not x.startswith("Run#"))
for k, v in grouped:
if not k:
v, nxt = "".join(v), next(grouped, " ")[1]
out.write("{}{}\n".format(v.rstrip(), "".join(map(str.strip, nxt))))
else:
out.writelines(v)
move(out.name,"file.txt")
输出:
Run#1 Step#1 > Connecting to server
Run#1 Step#2 > Connected OK
Run#1 Step#3 > Sending request: {"path": "/testpage","time": "2015-06-07T00:00:00.000Z"}
Run#1 Step#4 > Request sent OK
答案 2 :(得分:0)
1)拆分(“\ n”) 2)替换(“运行#”,“\ n运行#”) 3)删除第一行(“\ n”)
答案 3 :(得分:-1)
如果您的所有文件看起来与此文件完全相同,则可以使用此代码解决您的问题
file=open(filename,"r+")
lines = file.readlines()
for line in lines:
if (line.startswith("Run") and not "{" in line) or "}" in line:
print(line,end='')
else:
print(line.replace("\n",""), end='')