8

I have searched, but have come up short with an answer. I want to print the last line (or record) in a file; then print the first line using only awk. I know how to print first line:

NR == 1{print}

and last line

END{print}

However, how can I switch the positions? Is it even possible? I only get errors when I try to do so. Is there a way to integrate the

NR == 1{print}

command into the END command? Again, I only want to perform this in awk. Thanks!

2 Answers 2

18

Just save the first line to a variable

awk 'NR==1 {first = $0} END {print; print first}' file

Ex. given file as

line 1
line 2
line 3
line 4
line 5

then

$ awk 'NR==1 {first = $0} END {print; print first}' file
line 5
line 1
2
  • Being new to awk, I guess I didn't think I could do this, but you proved me wrong. Thank you! It worked on my end!
    – Nack
    Feb 4, 2017 at 4:29
  • +1 ; But a small enhancement : If file has only one line, then output has that line repeated; If file is empty, then output still has two empty lines. If that is not what is wanted, then we can check those two cases like this : awk 'NR==1 {first = $0; gotfirst = 1} END {if (gotfirst==1) {if (NR!=1) {print} print first}}' file
    – Prem
    Feb 4, 2017 at 18:19
1

AWK has getline() function which allows advancing to next line. Exit status of this line is zero when we cannot advance any further, i.e. we've reached end of file. Thus, the basic idea that we can use is to store first line into variable, keep track of current line, and keep trying to advance with getline. If we can't - print the variables in their desired order.

$ cat input.txt
first line
middle line
last line

$ awk 'NR==1{first=$0};{while (getline line); printf "%s\n%s\n",line,first}' input.txt                                   
last line
first line

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .