Use python to merge two rows of data into one row per group

1. Usage scenarios

Merge the odd-numbered and even-numbered lines of each regular group (a set of 2 lines) into one line, separated by spaces.

For example, if you use pssh to obtain the results in batches, you want to merge the ip line and the result line into one line (the premise is as described above)

[root@k8s-master1 tmp]# pssh -h iplist -i 'hostname'
[1] 18:12:42 [SUCCESS] 192.168.164.30
k8s-node1
[2] 18:12:42 [SUCCESS] 192.168.164.40
k8s-node2

Delete the redundant lines, and keep only one ip line and the result line you want, which can be easily achieved with grep -v, and then use the following script to merge the results. 

2, python script

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 将有规律的每组(一组2行)的单数行和双数行合并为一行,以空格分割
# 将你的pssh得到的数据放到result.txt中,然后运行本脚本。如果单数行不是[开头,则会报错提示你修改,修改好之后再重新运行本脚本

file_path = './result.txt'   # pssh生成的有规律的1行ip一行结果。如果不是这样有规律的需要整理。
x_index = 1

with open(file_path, encoding='utf-8') as file:
    content = file.read()
    for i in content.splitlines():
        if x_index % 2:
            if not i.startswith("["):    # 判断单行的开头如果不是以“["就说明有问题,程序自动退出。
                print(f"************Line {x_index} ERROR****************")
                exit(1)
            print(i, end=" ")    # 打印单数行后用空格结尾,便于连接双数行
        else:
            print(i)  # 打印双数行,自动换行
        x_index += 1

Note: Save your batch results in the same directory as this script, and the file name is result.txt, and then execute this script to print out the results 

3. Example of python script output result

[1] 18:12:42 [SUCCESS] 192.168.164.30 k8s-node1
[2] 18:12:42 [SUCCESS] 192.168.164.40 k8s-node2

Guess you like

Origin blog.csdn.net/xoofly/article/details/132048135