bash - 如何正确读取输入文件中的值在一个数组中
我试图编写一个脚本读取一个文件(多行) 这是“#”分开,并将它们放入一个数组中我可以匹配一些值。bash - 如何正确读取输入文件中的值在一个数组中
例输入文件:
us-east#1-1#abcdefg1234Ad
us-west#1-3#654kjhytgr
us-east#1-4#lkjhg765
我想要做的就是通过每行 阅读并给我根据我的输入参数($ 1)的比赛。 我被卡住,因为它只是评估第一行。
这里是我的代码:(执行:./myscript.sh美东1-3)
#!/usr/local/bin/bash
set -x
cluster=$1
KEY=./.keyfile
while IFS=#
declare -a arr=($(< $KEY)); do
if [[ ${arr[0]}-${arr[1]} == $1 ]]; then
echo "We have a match"
else
echo "No match"
exit 1
fi
done
set +x
我卡作为其仅仅只评估第一线。
因为你else
块你有exit
声明,想如果线路不匹配,循环将被终止由于exit 1
,所以进一步的迭代不会发生。
阅读第一行后,us-east-1-1
不等于us-east-1-3
,布尔false
,所以在你else
块你有exit
语句,所以终止
+ cluster=us-east-1-3
+ KEY=./file
+ IFS='#'
+ arr=($(< $KEY))
+ declare -a arr
+ [[ us-east-1-1 == us-east-1-3 ]]
+ echo 'No match'
No match
+ exit 1
您可以修改像下面这样你就会少用资源,逐行读取,而不是读整个文件到阵列
[[email protected] tmp]$ cat t.sh
#!/usr/bin/env bash
set -x
cluster="$1"
while IFS=# read -r field1 field2 restother; do
if [[ "$field1-$field2" == $1 ]]; then
echo "We have a match"
else
echo "No match"
fi
done < "file"
set +x
输出when cluster=us-east-1-3
[[email protected] tmp]$ bash t.sh us-east-1-3
+ cluster=us-east-1-3
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-1 == us-east-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-west-1-3 == us-east-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-4 == us-east-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ set +x
输出when cluster=us-west-1-3
[[email protected] tmp]$ bash t.sh us-west-1-3
+ cluster=us-west-1-3
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-1 == us-west-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-west-1-3 == us-west-1-3 ]]
+ echo 'We have a match'
We have a match
+ IFS='#'
+ read -r field1 field2 restother
+ [[ us-east-1-4 == us-west-1-3 ]]
+ echo 'No match'
No match
+ IFS='#'
+ read -r field1 field2 restother
+ set +x
您可以使用awk
这种类型的宗旨,合理,速度会更快
下面是一些例子
$ cat file
us-east#1-1#abcdefg1234Ad
us-west#1-3#654kjhytgr
us-east#1-4#lkjhg765
输出(当cluster="us-east-1-3"
)
$ awk -F'#' -v cluster="us-east-1-3" '{ print (cluster==$1"-"$2)? "We have a match": "No match"}' file
No match
No match
No match
输出(当cluster="us-west-1-3"
)
$ awk -F'#' -v cluster="us-west-1-3" '{ print (cluster==$1"-"$2)? "We have a match": "No match"}' file
No match
We have a match
No match
很好的输入将密钥文件中的数据读入数组arr中。我很感激并感谢您使用'awk'显示另一个解决方案。我可以使用它。 – noober
@noober,欢迎您 –
我阿克沙伊同意,这是与AWK解决了良好的问题。但是,如果你真的想单独壳里做它,它并不难:
#!/usr/bin/env bash
cluster="$1"
keyfile=keyfile.txt
ret=0
while IFS='#' read -r one two three; do
if [[ "${one}-${two}" = "$cluster" ]]; then
echo "match"
else
echo "no match"
ret=1
fi
done < "$keyfile"
exit $ret
的主要区别是,这是使用read
处理输入流是交给了while
循环,而不是重 - 为循环的每次运行评估$(< $keyfile)
表达式(我期望这会为每次运行提供第一行)。
修复了我当前的脚本,我会考虑使用'awk'来解决这个问题。谢谢。 – noober
您可以使用“readarray arr