在awk中设置一个外部变量 [英] Set an external variable in awk

查看:265
本文介绍了在awk中设置一个外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,其中我要计算data.txt中的列数.我的问题是我无法在awk脚本中设置x. 任何帮助将不胜感激.

I have written a script in which I want to count the number of columns in data.txt . My problem is I am unable to set the x in awk script. Any help would be highly appreciated.

while read p; do
  x=1;
  echo $p | awk -F' ' '{x=NF}'
  echo $x;
  file="$x"".txt";
  echo $file;
  done <$1

data.txt文件:

data.txt file:

4495125 94307025    giovy115p@live.it   94307025.094307025  12443
stazla  deva1a23@gmail.com  1992/.:\1
1447585 gioao_87@hotmail.it h1st@1
saknit  tomboro@seznam.cz   1233    1990

预期输出:

5.txt
3.txt
3.txt
4.txt

我的输出:

1.txt
1.txt
1.txt
1.txt

推荐答案

您只是不能Awk中设置的变量导入到shell上下文中.在您的示例中,在包含NFx内部设置的值不会在外部反映出来.

You just cannot import variable set in Awk to a shell context. In your example the value set inside x containing NF will be not reflected outside.

您需要使用命令替换($(..))语法来获取NF的值,并在以后使用它

Either you need to use command substitution($(..)) syntax to get the value of NF and use it later

x=$(echo "$p" | awk '{print NF}')

现在x将在每一行中包含列数.请注意,您不需要使用-F' ',它是awk中的默认定界符.

Now x will contain the column count in each of the line. Note that you don't need to use -F' ' which is the default de-limiter in awk.

除了您的要求之外,完全可以在Awk本身中完成.

Besides your requirement can be fully done in Awk itself.

awk 'NF{print NF".txt"}' file

此处,NF{..}是为了确保{..}内部的操作仅应用于非空行.对于每行,我们将打印长度,并在其后附加扩展名.txt.

Here the NF{..} is to ensure that the actions inside {..} are applied only to non-empty rows. The for each row we print the length and append the extension .txt along with it.

这篇关于在awk中设置一个外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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