我有一个看起来像这样的输出,其中第一个数字对应于下面类型的计数(例如,类型4的72,等等)
72
Type
4
51
Type
5
66
Type
6
78
Type
7
..etc
有没有办法将这些数据组织成如下所示:
Type 4 = 72 times
Type 5 = 51 times
Type 6 = 66 times
etc..
基本上,问题是如何使用单个数据列并使用bash,awk,python等将其排序/组织成更易读的内容(理想情况下,在bash中,但有兴趣知道如何在Python中执行) 。
谢谢。
答案 0 :(得分:4)
使用paste
从stdin连接3行,然后重新排列字段。
paste - - - < file | awk '{print $2, $3, "=", $1, "times"}'
答案 1 :(得分:2)
使用Python可以很容易地一次读取三行数据:
def perthree(iterable):
return zip(*[iter(iterable)] * 3)
with open(inputfile) as infile:
for count, type_, type_num in perthree(infile):
print('{} {} = {} times'.format(type_.strip(), type_num.strip(), count.strip()))
.strip()
调用删除任何额外的空格,包括每行输入文本末尾的换行符。
演示:
>>> with open(inputfile) as infile:
... for count, type_, type_num in perthree(infile):
... print('{} {} = {} times'.format(type_.strip(), type_num.strip(), count.strip()))
...
Type 4 = 72 times
Type 5 = 51 times
Type 6 = 66 times
Type 7 = 78 times
答案 2 :(得分:2)
试试这个awk one liner:
$ awk 'NR%3==1{n=$1}NR%3==2{t=$1}NR%3==0{print t,$1,"=",n,"times"}' file
Type 4 = 72 times
Type 5 = 51 times
Type 6 = 66 times
Type 7 = 78 times
它如何运作?
awk '
NR%3==1{ # if we are on lines 1,4,7, etc (NR is the record number (or the line number)
n=$1 # set the variable n to the first (and only) word
}
NR%3==2{ # if we are on lines 2,5,7, etc
t=$1 # set the variable t to the first (and only) word
}
NR%3==0{ # if we are on lines 3,6,9, etc
print t,$1,"=",n,"times" # print the desired output
}' file
答案 3 :(得分:2)
在Bash中:
#!/bin/bash
A=() I=0
while read -r LINE; do
if (( (M = ++I % 3) )); then
A[M]=$LINE
else
printf "%s %s = %s times\n" "${A[2]}" "$LINE" "${A[1]}"
fi
done
正在运行bash script.sh < file
:
Type 4 = 72 times
Type 5 = 51 times
Type 6 = 66 times
Type 7 = 78 times
注意:使用默认的IFS($' \t\n'
),read
默认会删除前导和尾随空格。