The END
section of Awk is for processing after you've looped through your whole file. For example:
awk ' BEGIN { total = 0 }
END { print "The total of column 1 is " total}
{
total += $1
print $0
}' file.txt
Here, I have a BEGIN
and END
clause. The BEGIN
clause runs before my file is processed, and basically initializes the variable total
to 0. (Not really necessary, but I wanted some sort of example).
The END
clause runs after I've processed all of the lines in my file. It prints out the amount of total
variable that I was calculating as I read in each line. My main part of my program (which is the last clause), simply adds column $1
to total and prints out the line.
What you want to do is change the way your line prints out as you read in that line. You want the last column (whatever that is) to print as your first column, and the first column to print as the last column. The NF
variable tell you the number of fields you have:
awk '{
for ( count = 1; count <= NF; count++ ) {
if ( count == 1 ) {
printf $NF " "
}
else if ( count == NF ) {
print $1
continue
}
else {
printf $count " "
}
}
}' test.txt
Here, I have nothing but my main clause. I have a for
loop that loops from the first to the last field of each line (Remember that each line is processed by my awk statement. If the count
is 1, I'm on my first field, and I print the last field ($NF
). If my count
is equal to the number of fields on that line, I print the first field ($1
). Otherwise, I print out the field itself.
This isn't the most compact form of awk
that could be produced, but it's easy to understand.
Does it work?
Here's my test file:
one two three four five six
alpha beta gamma
bob carol ted alice
uno dos tres quatro cinco ses
alpha bravo charlie delta echo
apple banana carrot darren eggplant fennel
And here's the output:
six two three four five one
gamma beta alpha
alice carol ted bob
ses dos tres quatro cinco uno
echo bravo charlie delta alpha
fennel banana carrot darren eggplant apple