Search code examples
linuxawkgawk

Weird awk output contains spaces


Why do I get those strange spaces?

echo "hello world" | awk 'BEGIN{FS=""} {$1=toupper($1); printf "%s\n", $0}'

I get the same result with the simpler way.

echo "hello world" | awk 'BEGIN{FS=""} {$1=toupper($1); print}'

Output:

H e l l o   w o r l d

Solution

  • Setting the field separator to the empty string has special significance: it reads revery single character into a separate field. Since the output field separator, OFS, is unchanged (a blank), your assignment reshuffles the complete record and inserts OFS between every single field.

    The first field/character is uppercased.

    Your first and second method are equivalent because print defaults to print $0, and printf "%s\n", $0 is equivalent to print $0.