如果n< m或n==0或m==0,则需要从massive_data.txt捕获包含“”的行,原型的周期如下所示。
cat massive_data.txt
Will_Liu> set Name.* xxx
============================================
Id Name Para status
============================================
1 name-1 xxxxx OK
2 name-2 xxxxx OK
3 name-3 xxxxx Not_OK
. ... .... OK
. ... .... OK
m name-m .... Not_OK
============================================
Total: m name attempted, n name set OK在上面的代码中,"m“和"n”是变量,如果n < m或n==0或m==0,则打印包含"Will_Liu>“的行;如果n==m和它们都为0,则跳过并忽略这种情况。
我只需使用"grep“和"sed”来掌握以下要点:
cat test.txt
Will_Liu> set Name_group1 xxx
============================================
Id Name Para status
============================================
1 name-1 xxxxx OK
2 name-2 xxxxx OK
3 name-3 xxxxx Not_OK
============================================
Total: 3 name attempted, 2 name set OK
Will_Liu> set Name_group2 yyy
============================================
Id Name Para status
============================================
1 name-4 xxxxx OK
2 name-5 xxxxx Not_OK
3 name-6 xxxxx Not_OK
============================================
Total: 3 name attempted, 1 name set OK我可以像这样使用"sed“和"grep”命令:
sed -n "/Total: 3 name attempted,/p" test.txt
Total: 3 name attempted, 2 name set OK
Total: 3 name attempted, 1 name set OK
grep -B 9 "Total: 3 name attempted" test.txt | sed -n '/Will_Liu>/p'
Will_Liu> set Name_group1 xxx
Will_Liu> set Name_group2 yyy在grep命令中,9是3+6,6基于结构的格式,它是一个固定的值。
那么,如何引入两个变量来定义"m“和"n”,并改进我的代码以从massive_data.txt获得预期的结果呢?我的预期输出:
Will_Liu> set Name1 xxx
Will_Liu> set Name2 yyy
Will_Liu> set Name3 zzz
. . .
. . .
. . . 发布于 2017-12-15 08:00:39
通常,您要打印的前一行都与另一个模式匹配。在这种情况下,最好是存储最后一个要打印的候选人,当你达到你的条件时,决定如何处理它。例如
awk '/^Will_Liu/{
last_will=$0
}
/^Total/{
m=$2; n=$5
if (m>n || (m==0 && n==0))
print last_will
}' file如果您真的没有任何模式来选择要打印的最后一个候选项,并且必须在对匹配的行数据进行数学运算之后确定要打印的行号,那么您可以双次传递一个文件,或者使用tac反转输入,或者将最后一行保留在散列数组中或任何类似的方法中。这些办法有时可能没有效率。例如,使用存储所有行,这对于您的情况是不建议的。
awk '{ line[NR]=$0 }
/^Total/{
m=$2; n=$5
if (m>n || (m==0 && n==0))
print line[NR-(m+5)]
}' filehttps://stackoverflow.com/questions/47827121
复制相似问题