前言:
cu上出了个shell题:
http://bbs.chinaunix.net/thread-2319120-1-1.html
第八题:GNU awk的$1=$1到底有什么作用?$0=$0呢?
这题问得相当的细致。可能很多人已经常用这二个赋值语句,却半知半解。以下分二部分对这个题目进行分析
建议没心情,没耐心,没兴趣的人,只需要了解下第一部分,看第二部分就表看了,很罗嗦的。
第一部分:能过man上边的解析,回签这二个赋值语句的功能
第二部分:awk部分源码解析(结点树简介,及域模块)
通过分析awk 域模块源码 ,了解awk的内部处理机制
参考程序及源码版本:gawk-3.1.5
=========================第一部分================================================
第一部分:GNU awk的$1=$1到底有什么作用?$0=$0呢?
首先了解一下一些知识,先翻一下man awk里的这段话:
assigning to a non-existent field (e.g., $(NF+2) = 5) increases the value of NF,
对不存在的域赋值,会增加NF值
creates any intervening fields with the null string as their value,
中间域默认为NULL字符串
and causes the value of $0 to be recomputed, with the fields being separated by the value of OFS.
$0会被根据OFS值重新计算,
References to negative numbered fields cause a fatal error.
引用负的域索引是无效的,并且会导致错误
Decrementing NF causes the values of fields past the new value to be lost,
减少NF值时,索引大于NF的域将会丢失
and the value of $0 to be recomputed, with the fields being separated </

本文详细分析了awk中的$1=$1和$0=$0的用途和原理。$1=$1会触发记录在下次引用$0时按OFS重构,改变输出分隔符;而$0=$0会根据FS重新分割记录,改变输入分隔符。这两种赋值操作涉及到记录分割和重构,是awk中重要的字段处理技巧。
最低0.47元/天 解锁文章
2913

被折叠的 条评论
为什么被折叠?



