English 中文(简体)
在 Awk 脚本中正确使用变量
原标题:Correctly use variable in awk script

我有一个有很多线条的文件,像这样:

 one     3456    orange
 two     6690    grape
 three   5570    apple
 four    6683    pear
 five    8847    cherry
 six     9035    banana

于是我写了个Awk脚本 来捕捉这个输出:

apple banana cherry

看起来是这样的:

awk  /three/ { a = $3}; /six/ { b = $3}; /five/ { c = $3} END {print  a" " b" "c}  <file

但这不是我一直使用 $3 - 我如何抓住这个变量来重新使用它?

最佳回答

这样做没有什么特别错误。如果使用变量,则必须重复。然而,您可以使用一个数组来积累你的数值。

以下是使用简单变量的例子 :

awk  {var = $3} /three/ {a = var}; /six/ {b = var}; /five/ {c = var} END {print a, b, c}  file

以下是使用数组的例子 :

awk  $1 ~ /^(three|six|five)$/ {arr[++c] = $3} END {for (i = 1; i <= c; i++) {printf "%s%s", delim, arr[i]; delim = OFS}; printf "
"}  file

您不需要使用重定向。 AWK 可以接受文件名作为参数 。

print 语句中,逗号可以替换 OFS (默认为空格) 的值,这样您就不需要使用 " "。

在数组版本中,您可以很容易地更改正则,因为它全部位于一个地方。

问题回答

暂无回答




相关问题
passing form variables into a url with php

I have the following form which allows a user to select dates/rooms for a hotel reservation. <form action="booking-form.php" method="post"> <fieldset> <div class="select-date">...

Error: "Cannot modify the return value" c#

I m using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable? public Point Origin { get; set; } Origin.X = 10; // fails with CS1612 Error ...

C-style Variable initialization in PHP

Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?

C#/.NET app doesn t recognize Environment Var Change (PATH)

In my C# app, I am programmatically installing an Oracle client if one is not present, which requires adding a dir to the PATH system environment variable. This all works fine, but it doesn t take ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

How to dynamically generate variables in Action Script 2.0

I have a for loop in action script which I m trying to use to dynamically create variable. Example for( i = 0 ; i &lt 3 ; i++) { var MyVar+i = i; } after this for loop runs, i would like to ...

热门标签