I am using GNU awk v4.2.0 from the Windows 7 x64 SP1 cmd.exe and ran into a problem with the following simple example:
# calculate the Greatest common divisor of each pair of inputs
BEGIN { RS="[\r\n]" } # added this
{
arg1 =$1; arg2 = $2;
if ((arg1 == "") || (arg2 == "")) { next } # and added this
while (arg1 != arg2)
{
if (arg1 > arg2)
arg1 -= arg2
else
arg2 -= arg1
}
print "The greatest common divisor of", $1, "and", $2, "is", arg1
}
and a DOS formatted (CR/LF line endings) input file as follows:
75 30
24 60
360 224
the numbers are separated by spaces. The original awk script did NOT have the BEGIN statement setting RS, also it did NOT have the if statement that tests if arg1 or arg2 are empty. The original script would produce the following output:
is 15eatest common divisor of 75 and 30
is 12eatest common divisor of 24 and 60
is 8reatest common divisor of 360 and 224
the results (15, 12 and 8) are in the wrong place because there is an unwanted carriage return in arg2.
To correct that problem, I added BEGIN { RS="[\r\n]" } which caused the output to be:
The greatest common divisor of 75 and 30 is 15
The greatest common divisor of and is
The greatest common divisor of 24 and 60 is 12
The greatest common divisor of and is
The greatest common divisor of 360 and 224 is 8
The greatest common divisor of and is
That made the value of the GCD appear at the end of the line where it's supposed to be but, it also caused unwanted/extraneous records to appear. To get rid of those I added the if ((arg1 == "") || (arg2 == "")) { next } which removed them.
Those steps caused the script to work as it should but, it seems to be a rather convoluted (not to mention undesirable) way of solving the problem.
my question is: is there a simpler, more natural, "awk like" way of making arg2 not include a carriage return in it ?