偷看下一行,但不消耗它 [英] Peek at next line, but don't consume it

查看:151
本文介绍了偷看下一行,但不消耗它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数getline 读取下一行,并递增1。 NR 计数器使用函数getline , AWK 继续与下一行的工作。这是在大多数情况下,所需的行为。

getline reads in the next line and increments the NR counter by 1. After using getline, awk resumes work with the next line. This is the desired behavior in most cases.

在我的特殊情况我只需要偷看下一行,并根据它的内容我看了下一行或我需要原路返回一行。

In my special situation I need only to peek the next line and depending on its content I read the next line or I need to backtrack one line.

我怎么能走回头路在 AWK 一条线?我尝试设置 NR 手工计数器 NR = NR-1 但这不起作用。或者是有只着眼于下一行不改变的方法 NR

How can I backtrack one line in awk? I tried setting the NR counter manually to NR=NR-1 but this doesn't work. Or is there a method that only looks at the next line without changing NR?

我需要一个系统的前瞻。简单地保存在一个变量的行并参照它以后在这种情况下不工作。我试图实施 AWK ,其中主文件可能包含许多子文件一个有文化的编程工具。这样的子文件开始像文件%:文件1行。达到这样一个文件的结尾,如果以较低的压痕或用线另一条一条线,如文件%:文件2。达到

I need a lookahead of one line. Simply saving the line in a variable and referring to it later does not work in this case. I am trying to implement a literate programming tool in awk, where a master file might contain many subfiles. Such a subfile begins with a line like "% file:file1". The end of such a file is reached, if a line with a lower indentation or another line with a line like "% file:file2" is reached.

该规则匹配的所有行 /%文件中设置:/ 未使用的,当我已经阅读函数getline这一行。这就是为什么我想重置 NR 到previous线,那么 AWK 会读行匹配 /%文件:/ 及相应的规则将被执行

The rule set for all lines matching /% file:/ is not used, when I have already read this line with getline. That's why I would like to reset NR to the previous line, then awk would read the line matching /% file:/ again and the appropriate rule would be executed.

推荐答案

这可能会接近你在找什么,不应该是昂贵的 SED 解决方案因为AWK保持一个指针到该文件函数getline 打开。

This may approach what you're looking for and shouldn't be as expensive as the sed solution since AWK maintains a pointer into the file that getline opens.

awk 'FNR == 1 {
         getline nextline < FILENAME
     }
     {
         getline nextline < FILENAME;
         print "currentline is:", $0;
         print "nextline is:   ", nextline
     }' input file

第一块读取的第一行和废物它

The first block reads the first line and wastes it.

在这种形式下,函数getline 不设置任何变量,如 NR FNR NF $ 1,0 。它只设置您提供的变量( nextline 在这种情况下)。

In this form, getline doesn't set any variables such as NR, FNR, NF or $0. It only sets the variable that you supply (nextline in this case).

请参阅this对于一些额外的信息。

See this for some additional information.

这篇关于偷看下一行,但不消耗它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆