在awk命令中使用`NF` [英] Use of `NF` in awk command

查看:154
本文介绍了在awk命令中使用`NF`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解两个命令之间的区别(我期望这两个命令具有相同的结果):

I am trying to understand what is the difference between two command (I was expecting same result from the two):

Case-I

echo 'one,two,three,four,five' |awk -v FS=,  '{NF=3}1'
one two three

Case-II

echo 'one,two,three,four,five' |awk -v FS=,  -v NF=3 '{$1=$1}1'
one two three four five

这是我目前的理解: $1=$1用于强制awk重建和使用定义的变量.我要像-v FS=","一样分配FS,实际上不同于-v NF=3.

Here is my current understanding: $1=$1 is used to force awk to reconstruct and use the variables defined. I am assigning FS like -v FS="," which is in effect unlike -v NF=3 .

问题:为什么NF=3不能像FS=,那样生效.

Question: Why NF=3 is not taking effect where as FS=, does.

推荐答案

https://www.gnu.org/software/gawk/manual/gawk.html#Options :

-v var = val
-分配 var = val

-v var=val
--assign var=val

在程序开始执行之前,将变量 var 设置为值 val .

Set the variable var to the value val before execution of the program begins.

https://www.gnu.org/software/gawk/manual/gawk.html#Fields :

NF是预定义变量,其值是当前记录中的字段数. awk每次读取记录时都会自动更新NF的值.

NF is a predefined variable whose value is the number of fields in the current record. awk automatically updates the value of NF each time it reads a record.

在第一个程序中,在读取每一行后执行{NF=3},覆盖NF.

In your first program, you execute {NF=3} after each line is read, overwriting NF.

在第二个程序中,最初通过-v设置了NF=3,但是当读取第一行输入时,该值将被awk覆盖.

In your second program, you initially set NF=3 via -v, but that value is overwritten by awk when the first line of input is read.

FS有所不同,因为awk从未设置此变量.它将保留您赋予它的任何价值.

FS is different because awk never sets this variable. It will keep whatever value you give it.

这篇关于在awk命令中使用`NF`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆