A for
or while
loop actually isn't needed. Either of these awk
commands will work:
awk 'BEGIN {print "title"}
{print "total",$1","$2}
END {print "end"}' list
or:
awk 'BEGIN {print "title"}
{printf "total %s,%s\n", $1, $2}
END {print "end"}' list
The BEGIN{print "title"}
prints the word title
once, before the data in the file is read.
{print "total",$1","$2}
prints the word total
followed by an unquoted comma representing a space between the values in the columns columns and then the columns themselves. This block is executed for each input line.
END{print "end"}
prints the word end
and the END of the file. END tells it to execute the block when the final input from the file has been read.
For the second command:
The only difference is:
{printf "total %s,%s\n", $1, $2}
This uses printf
instead of print
where the first argument defines the format.
%s,%s
tells it to print the values of $1
and $2
delimited by a comma and the \n
represents a new line so that it moves to the next line and prints the values of $1
and $2
until the end of the file.
Personally, I would use the second command with printf
as you can just use one set of quotes instead of quoting both total
and the comma. It is also more modular as you'll find from reading its man page. I'm only including the two commands to show the two different ways.
The output
title
total AAA,111
total BBB,222
total CCC,333
end
while
loop look like? – Kusalananda Mar 20 '19 at 06:32