我或多或少有一个文本文件:
log_file.txt
#Date: 2018-01-01 11:12:33
value1:aaa
value2:bbb
#Date: 2018-01-03 11:12:33
value1:aaa
value2:ccc
#Date: 2017-05-12 22:12:33
value1:ddd
value2:aaa
我正在寻找一个bash脚本,如:
#!/usr/bin/env bash
for group_lines in $(<something log_file.txt init_match("#.*") end_match("\n")>)
do
value1=$(echo -e "$group_lines" | head -1 | sed 's/value1://g')
value2=$(echo -e "$group_lines" | head -2 | tail -1 | sed 's/value2://g')
<do something value1 and value2>
done
我认为它带有一些awk代码。
答案 0 :(得分:1)
如果格式一致,则只需阅读文件并根据阅读内容采取措施即可。不要产生很多不必要的进程。
$: while IFS=: read key val
> do case $key in
> value1) value1=$val;;
> value2) value2=$val
> echo "<do something value1 and value2>: $value1 $value2";;
> esac
> done < log_file.txt
<do something value1 and value2>: aaa bbb
<do something value1 and value2>: aaa ccc
<do something value1 and value2>: ddd aaa
答案 1 :(得分:0)
我找到了。脚本是:
#!/usr/bin/env bash
for line in $(cat log_file.txt | awk '/#/{flag=1;next; print line; line=""} /^$/{flag=0; line=""} {if (flag == 1) { if (length(line) == 0) {line=$0} else {line=line"|#@#|"$0}}} END{if (flag == 1) {print line}}')
do
value1=$(echo $line | awk -F"[|]#@#[|]" '{print $1}')
value2=$(echo $line | awk -F"[|]#@#[|]" '{print $2}')
<do something value1 and value2>
done