I am trying to add last line to the file which I am creating. How is it possible to detect the last line of a file in awk before END
? I need to do this because the variables don't work in the END
block,
so I am trying to avoid using END
.
awk ' { do some things..; add a new last line into file;}'
before END
, I don't want this:
awk 'END{print "something new" >> "newfile.txt"}'
I know the answer was accepted, but it is simply wrong.
Because you do want to use awk as a parser and not as a code.
Awk should be used within some unix pipes and it should not be used within any logic.
I had the same problem and I solved it within awk like this:
nlines=
wc -l <file>
cat | awk -v nl=${nlines} '{if (nl != NR) {print $0,",","\";} else {print;}}' >> ${someout}
There is an important point here: pipes, flush, and RAM.
If you make awk to spit out its output you can pipe it to the next processor.
If you use getline, and in particular within a loop, you might not see the end.
getline should be used only for a line and an eventual dependency on the next line.
I love awk, but we cannot do everything with it!
EDITED:
For whom down-voted the answer, I just want to present this script:
And of course the first results:
Where you save about 10% of the time just because of the getline.
Consider this within more complex logic and you might get even a worst picture. In this plain version, memory consideration are not accounted. And seems they do not play a role for this simple version. But memory might also play a role if you get into more complex logic ...
Of course try it on your machine.
This is why I was suggesting to consider other options, in general.
By reading same file twice ( Recommended )
Using
getline
Print the previous line. When current line is 2, print line 1, when current line is 3, print line 2. .... till the end
You can get the number of lines in a file using
"wc -l" | getline filesize
in the begin block and useNR == filesize
to test the last line in the script body.You can use
ENDFILE
, it executes beforeEND
:ENDFILE exists in latest version of awk (>4.0 I think).
One option is to use
getline
function to process the file. It returns1
on sucess,0
on end of file and-1
on an error.Assuming
infile
with this data:Output will be: