Is there a way to determine whether the current line is the last line of the input stream?
相关问题
- In what practical case bool(std::ifstream) != std:
- UNIX Bash - Removing double quotes from specific s
- Split a .txt file based on content
- Using awk / sed to find and replace key value pair
- Filter ldapsearch with awk/bash
相关文章
- Node.js multiline input
- How to detect EOF in awk?
- Convert Text to Table (Space Delimited or Fixed le
- Combine split lines with awk / gawk
- Compare consecutive rows in awk/(or python) and ra
- How can I make a multiple-column output with '
- Run on all files in a directory, treating each sep
- Converting hexadecimal to decimal using awk or sed
To detect the last line of each file in the argument list the following works nicely:
gawk implementation has special rule called
ENDFILE
which will be triggered after processing every file in argument list. This works:more details you can find here>>
Detecting the EOF is not too reliable when multiple files are on the command line. Detecting the start of the file is more reliable.
To do this, the first file is special and we ignore the FNR==1.
After the first file then FNR==1 becomes the end of the previous file. last_filename always has the filename that you are processing.
Do your file processing after the else.
Do your EOF processing inside the else block, AND in the END block.
For multiple file sets, the else block executes at EOF for all but the last file. The last file is executed in the END block.
For single file sets, the else block doesn't get executed, and the END block is executed.
The special
END
pattern will match only after the end of all input. Note that this pattern can't be combined with any other pattern.More useful is probably the
getline
pseudo-function which resets$0
to the next line and return 1, or in case of EOF return 0! Which I think is what you want.For example:
If you are only processing one file, this would be equivalent:
These are the only sensible ways to do what you want, in order of best to worst:
I'm not even sure how to categorize this "solution"
The cool thing about this hack is that by assigning to
$0
, all the remaining declarative patterns and actions work, one line delayed. You can't get them to work for theEND
, even if you put theEND
on top, but you do have control on the last line and you haven't done anything else to it.