[英]how to use awk variables in shell
I am having the following structure(only one row) 我有以下结构(只有一行)
col1 col2 col3 col4
----------------------
12 34 14 10
what I have to do is I have to fetch col2 and col4 and used that value in shell. 我要做的是我必须获取col2和col4并在shell中使用该值。
a=$(awk 'NR<2{$2}')
b=$(awk'NR<2{$4}')
and I have to use a and b in my shell scripting. 而且我必须在外壳程序脚本中使用a和b。 but this is not a good idea as I am using
awk
two times instead I am fetching value like this . 但这不是一个好主意,因为我两次使用
awk
,而我却这样获取价值。
awk'NR<2{ a=$2;b=$4}'
but I dont know how can I use this a and b in my shell. 但我不知道如何在外壳中使用此a和b。
with eval you could assign more shell variables in one awk command. 使用eval可以在一个awk命令中分配更多的shell变量。 see the test below:
参见下面的测试:
kent$ echo $a,$b
,
kent$ cat test
col1 col2 col3 col4
----------------------
12 34 14 10
kent$ eval $(awk 'NR==3{print "a="$2;print "b="$4}' test)
kent$ echo $a,$b
34,10
note that I just copied your input example, with header/titles etc. so in my script the data line is NR=3. 请注意,我只是复制了带有标题/标题等的输入示例,因此在我的脚本中,数据行为NR = 3。 you can adjust it if it is not in your case.
您可以根据自己的喜好进行调整。
The read
built-in is useful here. 内置的
read
在这里很有用。
read _ a _ b _ < <( tail -n +3 data.txt) # Assign the columns you don't care about to _
echo $a,$b
This avoids the use of eval
, which should generally be avoided if you can find another option. 这样可以避免使用
eval
,如果可以找到另一个选项,通常应该避免使用eval
。
$ v=( $(awk 'NR==3{print $2 ORS $4}' file) )
$ a="${v[0]}"
$ b="${v[1]}"
$ echo "$a,$b"
34,10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.