Håkon Hægland
Håkon Hægland

Reputation: 40718

String concatenation in awk

Consider the following text file (test.txt) :

1 1 1
7 7 6

and the awk script (test.awk)

{
    print "$0 : ", $0
    lines=(lines $0)
    print "lines : ", lines
}

Then running:

awk -f test.awk test.txt

gives output

$0 :  1 1 1
lines :  1 1 1
$0 :  7 7 6
7 7 6 :  1 1 1

while the expected output should (as far as I can see) have been:

$0 :  1 1 1
lines :  1 1 1
$0 :  7 7 6
lines : 1 1 17 7 6

what am I missing here?

(I am using GNU Awk 3.1.8 on Ubuntu 12.04)

Upvotes: 0

Views: 2773

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

You've got DOS line endings in test.txt (CRLF, or \r\n at the end of each line).

Output with Unix line endings:

$0 :  1 1 1
lines :  1 1 1
$0 :  7 7 6
lines :  1 1 17 7 6

Output with DOS line endings:

$0 :  1 1 1
lines :  1 1 1
$0 :  7 7 6
7 7 6 :  1 1 1

Output with DOS line endings formatted with a hex-dump program:

0x0000: 24 30 20 3A 20 20 31 20 31 20 31 0D 0A 6C 69 6E   $0 :  1 1 1..lin
0x0010: 65 73 20 3A 20 20 31 20 31 20 31 0D 0A 24 30 20   es :  1 1 1..$0 
0x0020: 3A 20 20 37 20 37 20 36 0D 0A 6C 69 6E 65 73 20   :  7 7 6..lines 
0x0030: 3A 20 20 31 20 31 20 31 0D 37 20 37 20 36 0D 0A   :  1 1 1.7 7 6..
0x0040:

The 0D codes are the CR line endings.

Upvotes: 3

Related Questions