我是bash的新手,我正在尝试编写一个基本脚本来解析文件并将某些awk的元素存储在一个数组中,以并列方式并排打印。我已经定义了数组并且命令正常工作,但是我想使用getops来定义输出。抱歉,如果我不清楚,但希望psedocode会解释。
为任何帮助干杯,斯科特
#!/bin/bash
# Defined arrays
INPUTFILE=$2
ARRAYA=$(Code to process a file and extract column A)
ARRAYB=$(Code to process a file and extract column B)
ARRAYC=$(Code to process a file and extract column C)
ARRAYD=$(Code to process a file and extract column D)
# Define getops arguments
while getopts "A:B:C:D:" arg; do
case $arg in
A)
"I want to use $ARRAYA"
shift
;;
B)
"I want to use $ARRAYB"
shift
;;
C)
"I want to use $ARRAYC"
shift
;;
D)
"I want to use $ARRAYD"
shift
;;
esac
done
# Sample command construction for "myscript.sh -ABCD $INPUTFILE"
for ((i=0; i<=${#ARRAYA[@]}; i++)); do
echo "${ARRAYA[i]}" "${ARRAYB[i]}" "${ARRAYC[i]}" "${ARRAYD[i]}"
done
# Sample command construction for "myscript.sh -DCB $INPUTFILE"
for ((i=0; i<=${#ARRAYD[@]}; i++)); do
echo "${ARRAYD[i]}" "${ARRAYC[i]}" "${ARRAYB[i]}"
done
答案 0 :(得分:1)
这里的丑陋:使用bash间接变量
#!/bin/bash
ARRAYA=( a1 a2 a3 a4 a5 )
ARRAYB=( b1 b2 b3 b4 b5 )
ARRAYC=( c1 c2 c3 c4 c5 )
ARRAYD=( d1 d2 d3 d4 d5 )
order=()
while getopts ":ABCD" arg; do
case $arg in
A) order+=("ARRAYA") ;;
B) order+=("ARRAYB") ;;
C) order+=("ARRAYC") ;;
D) order+=("ARRAYD") ;;
esac
done
shift $((OPTIND - 1))
(( ${#order[@]} == 0 )) && exit
for ((i=0; i<=${#ARRAYA[@]}; i++)); do
for ary in "${order[@]}"; do
elem="${ary}[$i]"
echo -n "${!elem} "
done
echo
done
测试:
$ bash abcd.sh -A
a1
a2
a3
a4
a5
$ bash abcd.sh -BA
b1 a1
b2 a2
b3 a3
b4 a4
b5 a5
$ bash abcd.sh -BAC
b1 a1 c1
b2 a2 c2
b3 a3 c3
b4 a4 c4
b5 a5 c5
$ bash abcd.sh -DCBA
d1 c1 b1 a1
d2 c2 b2 a2
d3 c3 b3 a3
d4 c4 b4 a4
d5 c5 b5 a5
$ bash abcd.sh
(no output)