gawk: Concatenation
1
1 6.2.2 String Concatenation
1 --------------------------
1
1 It seemed like a good idea at the time.
1 -- _Brian Kernighan_
1
1 There is only one string operation: concatenation. It does not have
1 a specific operator to represent it. Instead, concatenation is
1 performed by writing expressions next to one another, with no operator.
1 For example:
1
1 $ awk '{ print "Field number one: " $1 }' mail-list
1 -| Field number one: Amelia
1 -| Field number one: Anthony
1 ...
1
1 Without the space in the string constant after the ':', the line runs
1 together. For example:
1
1 $ awk '{ print "Field number one:" $1 }' mail-list
1 -| Field number one:Amelia
1 -| Field number one:Anthony
1 ...
1
1 Because string concatenation does not have an explicit operator, it
1 is often necessary to ensure that it happens at the right time by using
1 parentheses to enclose the items to concatenate. For example, you might
1 expect that the following code fragment concatenates 'file' and 'name':
1
1 file = "file"
1 name = "name"
1 print "something meaningful" > file name
1
1 This produces a syntax error with some versions of Unix 'awk'.(1) It is
1 necessary to use the following:
1
1 print "something meaningful" > (file name)
1
1 Parentheses should be used around concatenation in all but the most
1 common contexts, such as on the righthand side of '='. Be careful about
1 the kinds of expressions used in string concatenation. In particular,
1 the order of evaluation of expressions used for concatenation is
1 undefined in the 'awk' language. Consider this example:
1
1 BEGIN {
1 a = "don't"
1 print (a " " (a = "panic"))
1 }
1
1 It is not defined whether the second assignment to 'a' happens before or
1 after the value of 'a' is retrieved for producing the concatenated
1 value. The result could be either 'don't panic', or 'panic panic'.
1
1 The precedence of concatenation, when mixed with other operators, is
1 often counter-intuitive. Consider this example:
1
1 $ awk 'BEGIN { print -12 " " -24 }'
1 -| -12-24
1
1 This "obviously" is concatenating -12, a space, and -24. But where
1 did the space disappear to? The answer lies in the combination of
1 operator precedences and 'awk''s automatic conversion rules. To get the
1 desired result, write the program this way:
1
1 $ awk 'BEGIN { print -12 " " (-24) }'
1 -| -12 -24
1
1 This forces 'awk' to treat the '-' on the '-24' as unary. Otherwise,
1 it's parsed as follows:
1
1 -12 ('" "' - 24)
1 => -12 (0 - 24)
1 => -12 (-24)
1 => -12-24
1
1 As mentioned earlier, when mixing concatenation with other operators,
1 _parenthesize_. Otherwise, you're never quite sure what you'll get.
1
1 ---------- Footnotes ----------
1
1 (1) It happens that BWK 'awk', 'gawk', and 'mawk' all "get it right,"
1 but you should not rely on this.
1