简体   繁体   中英

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

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 ??

This is literally comparing against {$myarr[i]} , not against the value associated with an entry in the shell variable by that name:

# 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).


Instead, pass your expanded value into awk separately:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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