简体   繁体   English

如何在bash中比较两个awk结果值

[英]How can I compare two awk result value in bash

Here's my code: 这是我的代码:

#!/bin/bash
filename=$1

declare -a myarr
myarr=($(awk '{print $2}' sim.count))
for((i=0 ;i<${#myarr[@]};i++))
do
#echo ${myarr[$i]}
#rm  "${myarr[$i]}"
awk '{if ($1 == "{$myarr[$i]}"){print $2}}' $filename > "${myarr[$i]}"
done

I store awk result into array and run loop to find if $filename 's column one has the same element then print column two 我将awk结果存储到数组中并运行循环以查找$ filename的第一列是否具有相同的元素,然后打印第二列

I have tried if ($1 == "a|||a"){print $2} and it work well, but if ($1 == "{$myarr[$i]}") not the result I want, anything wrong ?? 我已经尝试过if ($1 == "a|||a"){print $2}并且工作良好,但是if ($1 == "{$myarr[$i]}")不是我想要的结果,则出现任何错误??

This is literally comparing against {$myarr[i]} , not against the value associated with an entry in the shell variable by that name: 这实际上是与{$myarr[i]}进行比较,而不是与与该名称的shell变量中的条目相关联的值进行比较:

# original code: DOES NOT WORK (even if fixed to ${myarr[$i]})
awk '{if ($1 == "{$myarr[$i]}"){print $2}}'

This is because the double-quotes are still inside single-quotes, so the string is passed to awk without the shell expanding it -- and awk has no way of looking at shell variables (except ones in the environment, which requires explicit syntax to look up and doesn't apply to arrays anyhow). 这是因为双引号仍然在单引号内,因此该字符串被传递到awk而不用shell对其进行扩展-而且awk无法查看shell变量(环境中的变量除外,该变量需要显式语法以用于查找,并且不适用于数组)。


Instead, pass your expanded value into awk separately: 而是将您的扩展值分别传递到awk

awk -v tgt="${myarr[i]}" '{if ($1 == tgt) {print $2}}'

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

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