Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the last line in awk before END

Tags:

shell

awk

line

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"}'
like image 664
doniyor Avatar asked Aug 27 '12 12:08

doniyor


People also ask

How do I print the second last line in awk?

Use awk to generate the random record. Something like: $ awk -v min=1 -v max=1135 'BEGIN{srand(); print int(min+rand()*(max-min+1))}' then use the last line there.

How do I print the last row in Unix?

tail [OPTION]... [ Tail is a command which prints the last few number of lines (10 lines by default) of a certain file, then terminates. Example 1: By default “tail” prints the last 10 lines of a file, then exits.

How do I print last awk?

$NF as with any $fieldnumber usage in awk prints the value of the data element stored in the last field on every line. So if the first line in a file has 4 fields and the second line has 3, NF for each line is 4 and 3 respectively, and $NF is the respective values in $4 on the first line and $3 on the second line.

What is awk '{ print $3 }'?

txt. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.


1 Answers

One option is to use getline function to process the file. It returns 1 on sucess, 0 on end of file and -1 on an error.

awk '
    FNR == 1 {

        ## Process first line.
        print FNR ": " $0;

        while ( getline == 1 ) {
            ## Process from second to last line.
            print FNR ": " $0;
        }

        ## Here all lines have been processed.
        print "After last line";
    }
' infile

Assuming infile with this data:

one
two
three
four
five

Output will be:

1: one                                                                                                                                                                                                                                       
2: two                                                                                                                                                                                                                                       
3: three
4: four
5: five
After last line
like image 184
Birei Avatar answered Sep 19 '22 07:09

Birei