将 awk 设置为变量
我的代码如下所示:
awk -F'|' '{if($1 in a)print "duplicate found:" $2 " AND "a[$1];else a[$1]=$2 }' dump.txt
我需要将 $2 和 a[$2] 设置为变量。我该怎么做呢?
我正在获取一个包含以下内容的文件: 值“|” filename,然后我想将文件名和值设置为两个不同的变量。
I have code that looks like this:
awk -F'|' '{if($1 in a)print "duplicate found:" $2 " AND "a[$1];else a[$1]=$2 }' dump.txt
I need to set $2 and a[$2] to a variable. How would I go about doing this?
I am taking a file that contains: a value "|" filename and then I want to set the filename and the value to two different variables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
设置这些变量是什么意思?这些是环境变量。在 Awk 中,以美元符号开头且为数字的变量是为 AWK 保留的。这些是每行的字段值。例如:
命令
awk '{print $4}' test.txt
将打印出第四个字段:如您所见:它们不必设置。它们由 Awk 自动设置。
如果要设置环境变量,可以使用
-v
参数在上面,
search
是一个 Awk 变量,设置等于foo
>。由于 Awk 是一种编程语言,因此有时通过正确格式化程序可以更轻松地了解发生的情况:
程序正在读取每一行。每行由
|
分隔的两部分组成。看起来密钥的第一部分和第二部分是数据。我创建了一个如下所示的文本文件:第一行和最后一行应显示为重复项
我获取了您的程序并添加了一些调试行。这将帮助我跟踪它在程序中的位置:
而且,这是我的输出
取出调试行:
正如他们所说:
IT WORKS ON MY COMPUTER
(rimshot)
说真的,你的程序应该做什么,你认为它会做什么?有没有错误?您的程序看起来像广告中那样工作。
What do you mean Set those variables? Are these environment variables. In Awk, variables that start with a dollar sign and are numeric are reserved for AWK. These are the field values for each line. For example:
The command
awk '{print $4}' test.txt
will print out the fourth field:As you can see: They don't have to be set. They're automatically set by Awk.
If you want to set environment variables, you can use the
-v
parameterIn the above,
search
is an Awk variable that is set equal tofoo
.Since Awk is a programming language, it is sometimes easier to see what's going on by correctly formatting your program:
The program is taking each line. Each line consists of two parts separated by the
|
. It appears that the first part in the key and the second part is the data. I've created a text file that looks like this:The first and last line should show up as duplicates
I took your program and added a few debug lines. This will help me trace where it is in your program:
And, this is my output
Taking out the debug lines:
As they say:
IT WORKS ON MY COMPUTER
(rimshot)
Seriously, what is your program suppose to be doing, and what do you see it do? Are there any errors? Your program appears to work as advertised.
将它们设置为如下环境变量:
请注意,我所做的是“禁用”
$2
部分周围的单引号,并在它们周围添加双引号,以防环境变量包含空格 (哪个 awk 不希望看到将其参数分成几部分)。Set them to an environment variable like this:
Note that what I did was to "disable" the single-quotes around the
$2
parts, and add double-quotes around them in case the environment variable contains spaces (which awk wouldn't want to see splitting its argument into pieces).