简体   繁体   English

如何在shell脚本中将几个shell变量传递给awk?

[英]How to pass several shell variables to awk in shell script?

I have written a shell script to get any column. 我写了一个shell脚本来获取任何列。 The script is: 脚本是:

#!/bin/sh
awk '{print $c}' c=${1:-1}

So that i can call it as 这样我就可以称之为

ls -l | column 2

But how do i implement it for multiple columns? 但是如何为多列实现它? Say, it i want something like : 说,我想要类似的东西:

ls -l | column 2 3

In this case, I wouldn't use awk at all: 在这种情况下,我根本不会使用awk:

columns() { tr -s '[:blank:]' ' ' | cut -d ' ' -f "$@"; }

This uses tr to squeeze all sequences of whitespace to a single space, then cut to extract the fields you're interested in. 这使用tr将所有空格序列压缩为单个空格,然后cut以提取您感兴趣的字段。

ls -l | columns 1,5,9-

Note, you shouldn't parse the output of ls . 注意,您不应该解析ls的输出

awk -v c="3,5" '
    BEGIN{ split(c,a,/[^[:digit:]]+/) }
    { for(i=1;i in a;i++) printf "%s%s", (i==1?"":OFS), $(a[i]); print "" }
'

Use any non-digit(s) you like as the column number separator (eg comma or space). 使用您喜欢的任何非数字作为列号分隔符(例如,逗号或空格)。

ls -l | nawk -v r="3,5" 'BEGIN{split(r,a,",")}{for(i in a)printf $a[i]" ";print "\n"}'

Now you can simply change your r variable in shell script and pass it on. 现在,您可以简单地在shell脚本中更改r变量并将其传递。 or you can configure it in your shell script and use r=$your_list_var 或者您可以在您的shell脚本中配置它,并使用r=$your_list_var

What ever fields numbers are present in $your_list_var will be printed by awk command. $your_list_var中存在的字段编号将由awk命令打印。 The example above print 3rd and 5th fields of ls -l output. 上面的示例显示ls -l输出的第3和第5个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM