Way to print last line of a file then first line of a file in awk only

awk

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!

Best Answer

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
Related Question