在一段时间读取循环bash中从第4行获取变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在一段时间读取循环bash中从第4行获取变量相关的知识,希望对你有一定的参考价值。
有这个方案的txt文件:( 10k行中只有8个)
Paris: 405
Paris_average: 20
Paris_lenght: 30
score: 5.4
London: 605
London_average: 30
London_lenght: 30
score: 6.3
我需要做的是将“得分”变为一个变量,它始终位于第4行,并且其值大于“6.0”时,需要保留上面的3行。
因此,将示例作为输入,当脚本运行时,这是输出:
London: 605
London_average: 30
London_lenght: 30
score: 6.3
我已经考虑了4行的“while..read”循环,但我不知道如何继续前进。标签bash,但也赞赏perl解决方案。
短awk
解决方案:
awk '$1=="score:" && $2 > 6{ print r1 r2 r3 $0 }{ r1=r2; r2=r3; r3=$0 ORS }' file
$1=="score:" && $2 > 6
- 检查主要条件;$1
和$2
分别是第1和第2领域r1=r2; r2=r3; r3=$0 ORS
- 连续将3个随后的记录重新分配给变量r3
- >r2
- >r1
print r1 r2 r3 $0
- 打印相关的得分线以及之前的3条记录
样本输出:
London: 605
London_average: 30
London_lenght: 30
score: 6.3
奖金grep
解决方案:
grep -B3 '^score: [6-9]' file
如果模式qazxsw poi line作为4行部分/块内的第2行:
score:
以下grep -B1 -A2 '^score: [6-9]' file
可能会帮助你:
awk
现在添加非同一个内衬形式:
awk '{a[FNR]=$0;} /score:/ && $2>6 && FNR!=1{print a[FNR-3] RS a[FNR-2] RS a[FNR-1] RS $0}' Input_file
说明:
awk '
{
a[FNR]=$0
}
/score:/ && $2>6 && FNR!=1{
print a[FNR-3] RS a[FNR-2] RS a[FNR-1] RS $0
}
' Input_file
使用GNU awk并期望得分为awk '
{
a[FNR]=$0 ##Creating an array named a whose index is FNR(current line) and value is assigned as current line to it.
}
/score:/ && $2>6 && FNR!=1{ ##Checking condition here where checking if a line is having string score: in it and 2nd field is greater than 6 and line number is NOT one then do following:
print a[FNR-3] RS a[FNR-2] RS a[FNR-1] RS $0 ##Printing the value of a[FNR-3](3rd line from current line), RS(record seprator) a[FNR-2](2nd line from current line) a[FNR-1](prevoius line of current line)
}
' Input_file ##Mentioning Input_file name here too.
且小于10.0:
[0.9].[0-9]
解释:
$ gawk 'BEGIN{RS="
score: ...
"}RT~/[6789]./{printf "%s%s",$0,RT}' file
London: 605
London_average: 30
London_lenght: 30
score: 6.3
另一个使用缓冲和打印的常规aws:
$ gawk '
BEGIN {
RS="
score: ...
" # record separator is the score line
}
RT~/[6789]./ { # if the score starts with a digit 6-9
printf "%s%s",$0,RT # output the record
}' file
解释:
$ awk '{b=b $0 (NR%4?ORS:"")}!(NR%4){if($2>6)print b;b=""}' file
London: 605
London_average: 30
London_lenght: 30
score: 6.3
以上是关于在一段时间读取循环bash中从第4行获取变量的主要内容,如果未能解决你的问题,请参考以下文章