我如何比较 bash 中单个数组的值之间的不同参数?

How I compare different parameters among the values of a single array in bash?

我有一个数组,其中可以包含数量不确定的脚本,我正在尝试一个一个地比较这些脚本。像这样:

script1-script2
script1-script3
script1-script4
script2-script3
script2-script4
script3-script4
and so on...

脚本中我要比较的参数是:

到目前为止,我一直在数组中使用 for 循环,分别为每个脚本计算这些参数。但是我无法找到一种方法来按照我所说的方式比较每个脚本的参数。

我使用的结构是这样的:

echo "NUMBER OF TOTAL LINES";
for i in "${script[@]}"
do
cat $i | wc -l
done
echo "NUMBER OF COMMENTS";
for i in "${script[@]}"
do
grep -o '#' $i | wc -l
done 
echo "NUMBER OF IF COMMANDS"
for i in "${script[@]}"
do
grep -o 'if' $i | wc -l
done

我得到的输出是:

NUMBER OF TOTAL LINES
12
19
70
NUMBER OF COMMENTS
4
5
8
NUMBER OF IF COMMANDS
3
0
2

我需要的输出是(数组可以有数量不确定的脚本):

the script1 has 12 lines and the script2 has 19 lines
the script1 has 12 lines and the script3 has 70 lines
the script2 has 19 lines and the script3 has 70 lines

the script1 has 4 comments and the script2 has 5 comments
the script1 has 4 comments and the script3 has 8 comments
the script2 has 5 comments and the script3 has 8 comments

the script1 has 3 if commands and the script2 has 0 if commands
the script1 has 3 if commands and the script3 has 2 if commands
the script2 has 0 if commands and the script3 has 2 if commands

好吧,差不多但不完全是,请随意调整代码以满足您自己的需求。

#!/usr/bin/env bash

funct() {
  scripts=(
    script1 script2 script3 script4 script5
  )

  total_scripts=${#scripts[*]}

  for ((i = 0; i < total_scripts; i++)); do
    declare -A i_=(
    ['comments']=$(grep -c '#' "${scripts[$i]}")
    ['total_lines']=$(wc -l < "${scripts[$i]}")
    ['if_commands_total']=$(grep -Fc 'if ' "${scripts[$i]}")
  )
    for ((j = i + 1 ; j < total_scripts; j++)); do
        declare -A j_=(
        ['comments']="$(grep -c '#' "${scripts[$j]}")"
        ['total_lines']="$(wc -l < "${scripts[$j]}")"
        ['if_commands_total']="$(grep -Fc 'if ' "${scripts[$j]}")"
      )
      printf '%s ' "The ${scripts[$i]} has ${i_[total_lines]} lines"
      printf 'and %s\n' "The ${scripts[$j]} has ${j_[total_lines]} lines"
      printf '%s ' "The ${scripts[$i]} has ${i_[comments]} comments"
      printf 'and %s\n' "The ${scripts[$j]} has ${j_[comments]} comments"
      printf '%s ' "The ${scripts[$i]} has ${i_[if_commands_total]} if commands"
      printf 'and %s\n' "The ${scripts[$j]} has ${j_[if_commands_total]} if commands"
      done
  unset i_ j_ 'scripts[i]'
  scripts=("${scripts[@]}")
  total_scripts=${#scripts[*]}
  done
}

for item in lines comments if; do
  funct | grep "$item"
  echo
done
  • 需要 bash4+,因为关联数组。