关于awk中的$0

The simple statement 'print' with no items is equivalent to 'print $0': it prints the entire current record. To print a blank line, use 'print ""', where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic", as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error. Keep in mind that a space is printed between any two items.

 

print后面没有接任何东西时,相当于'print $0'。如果需要print空,可以使用print ""。使用双引号去输出字符串。如果忘记加双引号,会使print后面的变成awk expression。如果没有这个变量的话,一般就输出空了。

 

Creating a new field changes awk's internal copy of the current input record, which is the value of $0. Thus, if you do 'print $0' after adding a field, the record printed includes the new field, with the appropriate number of field separators between it and the previously existing fields.

 

awk中,可以使用诸如$6来加入新的field(如果NF5的话)。这时,$0的值也随之改变。

 

Advanced Notes: Understanding $0

It is important to remember that $0 is the full record, exactly as it was read from the input. This includes any leading or trailing whitespace, and the exact whitespace (or other characters) that separate the fields.

It is a not-uncommon error to try to change the field separators in a record simply by setting FS and OFS, and then expecting a plain 'print' or 'print $0' to print the modified record.

But this does not work, since nothing was done to change the record itself. Instead, you must force the record to be rebuilt, typically with a statement such as '$1 = $1', as described earlier.

 

$0是整条记录。当改变FSOFS时,不会马上使$0重建。而是需要使用$1=$1强制式$0 rebuild

 

例子:

bash-2.03$ echo "ttt|ddd|666"|awk -F"|" '{cur=$0;$NF="";after=$0;print}'

ttt ddd

由于$NF=""把最后一个field清空,$0重建,这时使用的OFS为默认值,空格。so

 

参考:

http://www.gnu.org/software/gawk/manual/gawk.html

posted @ 2013-02-27 13:20  酱油猫  阅读(1938)  评论(0编辑  收藏  举报