Arrays 从文件填充数组
我搜索过谷歌,但没有找到答案。我正在获取一个函数,用于从文件填充数组:Arrays 从文件填充数组,arrays,bash,populate,Arrays,Bash,Populate,我搜索过谷歌,但没有找到答案。我正在获取一个函数,用于从文件填充数组: #!/bin/bash PusherListV2=() PusherListV3=() getArray () { if ! [ -f $2 ]; then return 2 fi i=0 while read p; do PusherList$1[$i]="$p" ((i++))
#!/bin/bash
PusherListV2=()
PusherListV3=()
getArray () {
if ! [ -f $2 ]; then return 2
fi
i=0
while read p; do
PusherList$1[$i]="$p"
((i++))
done <$2
}
getArray V2 /tmp/test.txt
echo ${PusherListV2[@]}
有人能帮我吗?您不能在赋值中使用变量替换来构造变量名。这不起作用:
PusherList$1[$i]="$p"
替换为:
eval PusherList$1[$i]=\"\$p\"
甚至就这一点(正如shekhar suman所说,引用在这里并不是特别有用):
只要控制
$1
和$i
,这应该是eval
的安全使用readarray
有一个非常简单的解决方案。以下是测试文件:
$ cat file.tmp
first line
second line
third line
现在我读取文件并将行存储在数组中:
$ readarray mytab < file.tmp
如您所见,这些行与\n
一起存储。用-t
将其拆下
现在要解决您的问题,您可以使用新的nameref属性(bash 4.3+)在函数中通过引用传递数组,无需eval
:
PusherListV2=()
PusherListV3=()
getArray () array file
{
local -n array="$1" # nameref attribute
local file="$2"
test -f "$file" || return 2
readarray -t array < "$file"
}
getArray PusherListV2 /tmp/test.txt
echo "${PusherListV2[@]}" # always "" arround when using @
在函数中。如果我理解正确,您需要一个包含两个参数的函数:
- 第一个参数是一个字符串,它将被附加到
以获取数组名PusherList
- 第二个参数是文件名
getArray() {
[[ -f $2 ]] || return 2
# TODO: should also check file is readable
mapfile -t "PusherList$1" < "$2"
# TODO: check that mapfile succeeded
# (it may fail if e.g., PusherList$1 is not a valid variable name)
}
getArray(){
[[-f$2]| |返回2
#TODO:还应检查文件是否可读
地图文件-t“PusherList$1”<“$2”
#TODO:检查映射文件是否成功
#(如果PusherList$1不是有效的变量名,则可能会失败)
}
将-t
选项添加到mapfile
,以便修剪尾随的换行符
注意。这很可能是最有效的方法。删除推送列表$1[$i]=“$p”中的双引号!它应该是简单的
PusherList$1[$i]=$p
。那么PusherListV2=($(cat test.txt))
呢?根本不需要名称引用!如果你想避免全局变量,它们是可以的。readarray-t“$1”<“$file”
会完全避免nameref。事实上,如果你想在函数中的数组上做些什么,你可以使用nameref和局部变量。我想在其他函数中使用全局变量。。。这就是我不使用局部变量的原因。我使用的是debian服务器——Bash4.2。37@EdouardThiel是的,通常首选名称mapfile
。
$ declare -p mytab
declare -a mytab='([0]="first line
" [1]="second line
" [2]="third line
")'
PusherListV2=()
PusherListV3=()
getArray () array file
{
local -n array="$1" # nameref attribute
local file="$2"
test -f "$file" || return 2
readarray -t array < "$file"
}
getArray PusherListV2 /tmp/test.txt
echo "${PusherListV2[@]}" # always "" arround when using @
local -n array="PusherList$1" # nameref attribute
getArray() {
[[ -f $2 ]] || return 2
# TODO: should also check file is readable
mapfile -t "PusherList$1" < "$2"
# TODO: check that mapfile succeeded
# (it may fail if e.g., PusherList$1 is not a valid variable name)
}