我在 logfmt 中有一个日志文件,其中包含如下行
duration=38.924266437s job=267842 project=507
duration=38.924266437s job=267842 project=507
duration=2m56.408984141s job=267850 project=745
duration=2m56.408984141s job=267850 project=745
duration=3m38.211342699s job=267846 project=173
duration=3m38.211342699s job=267846 project=173
duration=3m38.690043053s job=267843 project=173
duration=3m38.690043053s job=267843 project=173
...
如何将持续时间值转换为一种测量单位(秒或分钟)?
答案1
使用awk
:
awk -F'[= ]' '{
n=split($2, a, "m")
sub($2, sprintf("%.9f", (n==1 ? a[1] : 60*a[1]+a[2])))
}1' file
输出:
duration=38.924266437 job=267842 project=507
duration=38.924266437 job=267842 project=507
duration=176.408984141 job=267850 project=745
duration=176.408984141 job=267850 project=745
duration=218.211342699 job=267846 project=173
duration=218.211342699 job=267846 project=173
duration=218.690043053 job=267843 project=173
duration=218.690043053 job=267843 project=173
- 使用
=
和作为字段分隔符,第二个字段
$2
包含目标字符串,例如38.924266437s
。 - 将 string 上的第二个字段拆分
m
为 arraya
,n
是数组的长度。 - 计算新值:如果
n
是1
,则使用第一个数组值(秒),否则根据两个数组值计算秒。 - 将第二个字段替换为浮点格式的计算值。
- 打印记录。
答案2
这个怎么样?
#!/bin/bash
regex_min='duration=([0-9]+)m'
regex_sec='([0-9]+)\.([0-9]+)s'
while read -r line; do
[[ $line =~ $regex_sec ]]
sec=${BASH_REMATCH[1]}
frac=${BASH_REMATCH[2]}
if [[ $line =~ $regex_min ]]; then
sec=$(( sec + 60*${BASH_REMATCH[1]} ))
fi
echo $line: $sec.$frac
done
将其另存为process.sh
然后运行:
cat myfile | bash process.sh
以下是您通过示例数据得到的输出:
duration=38.924266437s job=267842 project=507: 38.924266437
duration=38.924266437s job=267842 project=507: 38.924266437
duration=2m56.408984141s job=267850 project=745: 176.408984141
duration=2m56.408984141s job=267850 project=745: 176.408984141
duration=3m38.211342699s job=267846 project=173: 218.211342699
duration=3m38.211342699s job=267846 project=173: 218.211342699
duration=3m38.690043053s job=267843 project=173: 218.690043053