繁体   English   中英

在一会儿读取循环bash中从第4行获取变量

[英]Get variable from 4th line in a while read loop bash

使用以下方案获得了一个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

我需要做的是获取一个“ score”变量,该变量始终位于第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分别是第一个字段和第二个字段
  • r1=r2; r2=r3; r3=$0 ORS 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

如果图案score:线与4线段/块一起作为第二行:

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

说明:

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.

使用GNU awk并期望分数的形式为[0.9].[0-9]且小于10.0:

$ gawk 'BEGIN{RS="\nscore: ...\n"}RT~/[6789]\./{printf "%s%s",$0,RT}' file
London: 605
London_average: 30
London_lenght: 30
score: 6.3

解释:

$ gawk '
BEGIN {
    RS="\nscore: ...\n"   # 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

使用缓冲和打印的reqular awk的另一个:

$ 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

解释:

$ awk '
{
    b=b $0 (NR%4?ORS:"")  # buffer records
}
!(NR%4) {                 # on every 4th record
    if($2>6)              # if condition met
        print b           # print buffer
    b=""                  # reset buffer
}'  file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM