I have a scenario where i did array_1 [index] value check with array_2 [index] value.
My below code is working like a charm, but is there any different approach to achieve the same?
I'm looking for a unique way of handling 2 array list values and compare, with few lines of code.
My code:
#!/bin/bash
array_1=(4 4 3)
array_2=(4 1 3)
i=''
j=''
count=0
for i in "${array_1[@]}"
do
i="cmd ${array_1[$count]}"
j="cmd ${array_2[$count]}"
if [ "$i" -eq "$j" ]
then
echo "${array_1[$count]} match with ${array_2[$count]}"
count=$(( count + 1 ))
else
echo "${array_1[$count]} does not match with ${array_2[$count]}"
exit 1
fi
done
Note: Code is checked with shellcheck.net , no error found.
If two arrays have different values, below is the output:
array_1=(4 4 3)
array_2=(4 1 3)
Output:
4 match with 4
4 does not match with 1
If two arrays have the same values, below is the output:
array_1=(4 4 3)
array_2=(4 4 3)
Output:
4 match with 4
4 match with 4
3 match with 3
You added awk
to your question.
With awk
you could do:
awk 'FNR==NR{x[FNR]=$1; next}
x[FNR]==$1{print x[FNR] " match with " $1; next}
{print x[FNR] " does not match with " $1}
' <(printf "%s\n" "${array_1[@]}") <(printf "%s\n" "${array_2[@]}")
Or with paste
and awk
you can do:
paste <(printf "%s\n" "${array_1[@]}") <(printf "%s\n" "${array_2[@]}") | awk '
$1==$2{print $1 " match with " $2; next}
{print $1 " does not match with " $2}'
Either prints (with the two arrays in your example):
4 match with 4
4 does not match with 1
3 match with 3
If you want to exit after the first no match, just add exit
after the print
:
awk 'FNR==NR{x[FNR]=$1; next}
x[FNR]==$1{print x[FNR] " match with " $1; next}
{print x[FNR] " does not match with " $1; exit 1}
' <(printf "%s\n" "${array_1[@]}") <(printf "%s\n" "${array_2[@]}")
Explanations
The construct of printf "%s\n" "${array_1[@]}"
creates the output of array_1
as a string separated by \n
:
printf "%s\n" "${array_1[@]}"
4
4
3
The construct of:
cmdX <(cmdY)
Does the following:
cmdY
andcmdX
as an argument to then be read as file.paste
takes two file-like inputs and creates a two column single output:
paste <(printf "%s\n" "${array_1[@]}") <(printf "%s\n" "${array_2[@]}")
4 4
4 1
3 3
Once you have the arrays side by side or as if two files then comparing the two with awk
diff
comm
perl
or ruby
is trivial.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments