gpt4 book ai didi

linux - 从 bash 中分离出时间戳/键/值对

转载 作者:太空宇宙 更新时间:2023-11-04 05:02:49 25 4
gpt4 key购买 nike

嗨,我有这个充满数据的文件;时间戳基本上是该行的开头。我需要分解文件并单独打印每一行。如何仅使用 bash 和(如果需要)标准 UNIX 工具(sed、awk 等)来完成此任务?

时间戳字段从 08:30:00:324810: 开始 .. 示例 17:30:00:324810: 。时间戳后面的字段数量各不相同;所以可能有 1 到 x 个字段。所以我需要找到时间戳格式,然后插入分页符。

08:30:00:324810: usg_07Y  BidYield=1.99788141 Bid=99.20312500 08:30:00:325271: usg_07Y
AskYield=1.98578274 Ask=99.28125000 08:30:00:325535: usg_10Y Ask=0.00000000 08:30:01:324881:
usg_07Y BidYield=2.02938740 AskYield=1.97127853 Bid=99.00000000 Ask=99.37500000 08:30:01:377021:
usg_05Y Bid=0.00000000 Ask=0.00000000

提前谢谢你马特

最佳答案

这是相当微不足道的。将文件读入数组,找到时间戳,在其之前输出换行符:

#!/bin/bash

set -f # inhibit globbing (filename expansion)
declare -i cnt=0 # simple counter

a=( $(<"$1") ) # read file into array
for i in "${a[@]}"; do # for each word in file
if [ "$cnt" -gt 0 ]; then # test counter > 0
# if last char ':', then output newline before word
[ ${i:(-1):1} = ':' ] && printf "\n%s" "${i}" || printf " %s" "$i"
else
printf "%s" "$i" # if first word, just print.
fi
((cnt++))
done
printf "\n"

使用/输出:

$ bash parsedtstamp.sh filename.txt
08:30:00:324810: usg_07Y BidYield=1.99788141 Bid=99.20312500
08:30:00:325271: usg_07Y AskYield=1.98578274 Ask=99.28125000
08:30:00:325535: usg_10Y Ask=0.00000000
08:30:01:324881: usg_07Y BidYield=2.02938740 AskYield=1.97127853 Bid=99.00000000 Ask=99.37500000
08:30:01:377021: usg_05Y Bid=0.00000000 Ask=0.00000000

我添加了一个计数器变量,以便仅输出换行符(如果不是第一个单词)。

<小时/>

避免临时数组存储(针对大文件)的替代版本

虽然 Bash 中的数组大小没有限制,但如果您发现自己正在解析数百万行文件,最好避免将所有行存储在内存中。这可以通过简单地处理从文件中读取的行来完成。这只是一种在不使用数组作为中间存储的情况下做同样事情的方法:

#!/bin/bash

set -f # inhibit globbing (filename expansion)
declare -i cnt=0 # simple counter

# read each line in file
while read -r line_entries || [ -n "$line_entries" ]; do
for i in $line_entries; do # for each word in line (no quotes for word splitting)
if [ "$cnt" -gt 0 ]; then # test counter > 0
# if last char ':', then output newline before word
if [ ${i:(-1):1} = ':' ]; then
printf "\n%s" "${i}"
else
printf " %s" "$i"
fi
else
printf "%s" "$i" # if first word, just print.
fi
((cnt++)) # increment counter
done
done <"$1"

printf "\n"

关于linux - 从 bash 中分离出时间戳/键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27323412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com