打印作为变量传递的字段列表 [英] Print a list of fields passed as a variable

查看:34
本文介绍了打印作为变量传递的字段列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件说a.txt,下面是文件的内容:

bob 1 100            
lincoln 2 200  
chris 3 300        

文件内容之间用空格分隔.

使用awk,我可以访问每一列.使用以下命令 打印用逗号分隔的第一和第三列:

cat a.txt | awk ' { print $1","$3} '

我成功了.

现在,我想从另一个Shell脚本动态传递条件.说标准是指-$1","$3.

我尝试了以下命令,但是没有用.

myvar="$1"   
awk -v a="$myvar"  ' { print a } ' a.txt

但这将打印$1 3次,因为a.txt中有三行.

如何以这种方式将字段列表传递给awk?

解决方案

此处的问题是,传递给awk的变量中的$是按字面意义解释的-不能用于引用特定字段./p>

对于单个字段,您可以使用以下内容:

awk -v field=1 '{ print $field }' file
bob
lincoln
chris

对于多个字段,这有点复杂:

awk -v fields="1 3" 'BEGIN{ n = split(fields,f) }
    { for (i=1; i<=n; ++i) printf "%s%s", $f[i], (i<n?OFS:ORS) }' file
bob 100
lincoln 200
chris 300

字段列表以字符串形式传递,该字符串被拆分为一个数组.然后使用printf循环遍历该数组,以输出每个字段,然后输出数组分隔符OFS或输出记录分隔符ORS,具体取决于它是否为最后一个字段. 要用逗号分隔字段,可以将-v OFS=,作为选项传递.

I have a file say a.txt and below are the contents of it:

bob 1 100            
lincoln 2 200  
chris 3 300        

The file contents are separated by space.

Using awk, I could access each column. Using below command to print 1st and 3rd columns separated by comma:

cat a.txt | awk ' { print $1","$3} '

and I was successful.

Now I want to pass the criteria dynamically from another shell script. By saying criteria I mean - $1","$3.

I tried the below command but it didn't work.

myvar="$1"   
awk -v a="$myvar"  ' { print a } ' a.txt

but this is printing $1 3 times as there are three rows in a.txt.

How can I pass a list of fields to awk in this way?

解决方案

The problem here is that the $ in the variable you have passed to awk is interpreted literally - it cannot be used to refer to a specific field.

For a single field, you could use something like this:

awk -v field=1 '{ print $field }' file
bob
lincoln
chris

For multiple fields, this is a little more complicated:

awk -v fields="1 3" 'BEGIN{ n = split(fields,f) }
    { for (i=1; i<=n; ++i) printf "%s%s", $f[i], (i<n?OFS:ORS) }' file
bob 100
lincoln 200
chris 300

The list of fields is passed as a string, which is split into an array. The array is then looped through, using printf to output each field, followed by either the Output Field Separator OFS or the Output Record Separator ORS, depending on whether it's the last field or not. To separate the fields with a comma, you can pass -v OFS=, as an option.

这篇关于打印作为变量传递的字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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