将第二个模式转换为awk中的毫秒 [英] Converting second pattern to millisecond in awk
问题描述
我有一个文件,文件中包含模式"s",我需要乘以1000转换为"ms".我无法执行此操作.请帮助我.
I have file which is having pattern 's' , I need to convert into 'ms' by multiplying by 1000. I am unable to do it. Please help me.
file.txt
First launch 1
App: +1s170ms
First launch 2
App: +186ms
First launch 3
App: +1s171ms
First launch 4
App: +1s484ms
First launch 5
App: +1s227ms
First launch 6
App: +204ms
First launch 7
App: +1s180ms
First launch 8
App: +1s177ms
First launch 9
App: +1s183ms
First launch 10
App: +1s155ms
我的代码:
awk 'BEGIN { FS="[: ]+"}
/:/ && $2 ~/ms$/{vals[$1]=vals[$1] OFS $2+0;next}
END {
for (key in vals)
print key vals[key]
}' file.txt
预期输出:
App 1170 186 1171 1484 1227 204 1180 1177 1183 1155
即将到来的输出
App 1 186 1 1 1 204 1 1 1 1
如果出现第二种模式,如何将上述模式s转换为"ms".
How to convert in above pattern 's' to 'ms' if second pattern comes .
推荐答案
在这里我将尝试做一些解释,然后将其应用于您的情况.
What I will try to do here is explain it a bit generic and then apply it to your case.
问题:我有一个字符串,格式为
123a456b7c8d
,其中数字是任意长度的数字整数值,字母是相应的单位.我还具有将单位a,b,c,d
转换为单位f
的转换因子.如何将其转换为单一数量的f
单位?
Question: I have a string of the form
123a456b7c8d
where the numbers are numeric integral values of any length and the letters are corresponding units. I also have conversion factors to convert from unita,b,c,d
to unitf
. How can I convert this to a single quantity of unitf
?
示例:从1s183ms
到1183ms
策略:
- 为每个字符串创建一组键值对
'a' => 123
,'b' => 456
,'c' => 7
和'd' => 8
- 将每个值乘以corect转换因子
- 将数字加在一起
- create per string a set of key-value pairs
'a' => 123
,'b' => 456
,'c' => 7
and'd' => 8
- multiply each value with the corect conversion factor
- add the numbers together
假设我们使用awk,并且键值对存储在数组a
中,并且键作为索引.
Assume we use awk and the key-value pairs are stored in array a
with the key as an index.
-
从
str
提取键值对:
function extract(str,a, t,k,v) {
delete a; t=str;
while(t!="") {
v=t+0; match(t,/[a-zA-Z]+/); k=substr(t,RSTART,RLENGTH);
t=substr(t,RSTART+RLENGTH);
a[k]=v
}
return
}
转换和求和:这里我们假设我们有一个数组f
,其中包含转换因子:
convert and sum: here we assume we have an array f
which contains the conversion factors:
function convert(a,f, t,k) {
t=0; for(k in a) t+=a[k] * f[k]
return t
}
完整代码(以OP为例)
The full code (for the example of the OP)
# set conversion factors
BEGIN{ f['s']=1000; f['ms'] = 1 }
# print first word
BEGIN{ printf "App:" }
# extract string and print
/^App/ { extract($2,a); printf OFS "%dms", convert(a,f) }
END { printf ORS }
输出:
App: 1170ms 186ms 1171ms 1484ms 1227ms 204ms 1180ms 1177ms 1183ms 1155ms
这篇关于将第二个模式转换为awk中的毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!