Peek at next line, but don't consume it

丶灬走出姿态 提交于 2019-11-30 17:52:51

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.

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).

See this for some additional information.

This is a bit of a hack and is fairly expensive, but for small files does give you a lookahead:

cmd="sed -n " NR + 1 "p " FILENAME; cmd | getline nextline

That will take the current value of NR and use sed to extract line NR + 1 from the input file. This is expensive because sed will read through the entire file each time you do a lookahead (you can alleviate that slightly by adding a 'q' command to sed). The variable nextline will be set to the next line of the file, and will be blank on the last line.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!