awk里面的一些隐藏特性
时间:2007-01-29 来源:awk就是awp加ak
awk里面的一些隐藏特性,只是简单的小结
1、print, printf, sub 缺省参数 $0
CODE:
[Copy to clipboard]
echo "abc" |awk '{ print; }'
echo "abc" |awk '{ printf; }'
echo "abc" |awk '{ sub(/abc/, "efg"); print; }'
相当于
CODE:
[Copy to clipboard]
echo "abc" |awk '{ print $0; }'
echo "abc" |awk '{ printf $0; }'
echo "abc" |awk '{ sub(/abc/, "efg", $0); print; }'
2、split缺省分隔符 FS
CODE:
[Copy to clipboard]
echo "abc cde efg d" |awk '{ print split($0, arr); }'
相当于
CODE:
[Copy to clipboard]
echo "abc cde efg d" |awk '{ print split($0, arr, FS); }'
3、代码块外面的表达式,默认行为是 print $0
CODE:
[Copy to clipboard]
echo "abc" |awk 'count=2'
相当于
CODE:
[Copy to clipboard]
echo "abc" |awk 'count=2 { print $0; }'
或者
CODE:
[Copy to clipboard]
echo "abc" |awk '{ if (count=2) print $0; }'
如果还不好理解,请看下面:
CODE:
[Copy to clipboard]
echo "abc" |awk '
{ count=3; $0="abc1"; } count==3;
{ count=4; $0="abc2"; } count==3;
{ count=5; $0="abc3"; } count==5;
'
4、当修改 NF、$i 之后,awk 会使用 OFS 重新组织 $0
CODE:
[Copy to clipboard]
$echo "abc cde" |awk 'BEGIN{ OFS="|"; } $2="eee"'
abc|eee
$echo "abc cde" |awk 'BEGIN{ OFS="|"; } NF=3'
abc|cde|
注意:对 NF 的修改,目前仅用 gnu awk 测试有效,其他awk 输出不变:
abc cde
1、print, printf, sub 缺省参数 $0
CODE:
[Copy to clipboard]
echo "abc" |awk '{ print; }'
echo "abc" |awk '{ printf; }'
echo "abc" |awk '{ sub(/abc/, "efg"); print; }'
相当于
CODE:
[Copy to clipboard]
echo "abc" |awk '{ print $0; }'
echo "abc" |awk '{ printf $0; }'
echo "abc" |awk '{ sub(/abc/, "efg", $0); print; }'
2、split缺省分隔符 FS
CODE:
[Copy to clipboard]
echo "abc cde efg d" |awk '{ print split($0, arr); }'
相当于
CODE:
[Copy to clipboard]
echo "abc cde efg d" |awk '{ print split($0, arr, FS); }'
3、代码块外面的表达式,默认行为是 print $0
CODE:
[Copy to clipboard]
echo "abc" |awk 'count=2'
相当于
CODE:
[Copy to clipboard]
echo "abc" |awk 'count=2 { print $0; }'
或者
CODE:
[Copy to clipboard]
echo "abc" |awk '{ if (count=2) print $0; }'
如果还不好理解,请看下面:
CODE:
[Copy to clipboard]
echo "abc" |awk '
{ count=3; $0="abc1"; } count==3;
{ count=4; $0="abc2"; } count==3;
{ count=5; $0="abc3"; } count==5;
'
4、当修改 NF、$i 之后,awk 会使用 OFS 重新组织 $0
CODE:
[Copy to clipboard]
$echo "abc cde" |awk 'BEGIN{ OFS="|"; } $2="eee"'
abc|eee
$echo "abc cde" |awk 'BEGIN{ OFS="|"; } NF=3'
abc|cde|
注意:对 NF 的修改,目前仅用 gnu awk 测试有效,其他awk 输出不变:
abc cde
|
相关阅读 更多 +