linux 如何将值存储到数组中

linux 如何将值存储到数组中

我无法将值保存在数组中。以下是文件数据:

123|23.23|2.34|3.45|2019-20-1

我想要数组中的第二个、第三个和第四个值。该代码应该是通用的,以便将来我可以选择 4 个参数而不是 3 个或不同的字段组合。

array ={23.33 2.34 3.45 2019-20-1}

部分工作代码:

declare -a alpha=()

alpha=($(awk '{n = split($0, t, "|")
for(i = 0; ++i <= n;) print t[i]}' <<<'$2|$3|$4'))
echo "$alpha[@]"

我将输入传递为:'$2|$3|$4'

我想要像下面这样的数组输出

alpha={$2 $3 $4}

当我打印时,echo "${alpha[@]}"应打印所有值

输出 : $2 $3 $4

*注意:输出应该在两个值之间留有空格,以便我可以在进一步的代码中使用这些值作为循环来获取另一个值

答案1

bashread命令可以将字段存储到数组中:

while IFS='|' read -r -a fields; do
    # do stuff with the elements of "${fields[@]}"
done < file

答案2

这适用于你的情况

alpha=( $(awk -F'|'  '{ for(i=1;++i<=NF;) printf $i" "}' yourfile ) )

使用 NF(字段编号而不是硬编码字段编号)。

答案3

#!/bin/bash

# Read the data into the array fields from the
# file called "file". This assumes that the data
# is a single line with fields delimited by
# |-characters.
mapfile -d '|' -t fields <file

# The last entry in the fields array will quite
# likely have a trailing newline at the end of it.
# Remove that newline if it exists.
fields[-1]=${fields[-1]%$'\n'}

# These are the column numbers from the original
# data that we'd like to keep.
set -- 2 3 4

# Extract those columns from the fields array. Note
# that we have to decrement the numbers by one as
# arrays in bash are indexed from zero.
for column do
        array+=( "${fields[column-1]}" )
done

# Output the elements of the resulting array:
printf '%s\n' "${array[@]}"

# For outputting with spaces in-between the values
# rather than newlines:
printf '%s\n' "${array[*]}"

没有理由输出如果您要将它们用于其他用途,请在末尾添加数组的值。 说你想以特定格式输出值(它们之间有空格)意味着你只是要解析它们再次和其他一些代码。那是完全没有必要的,因为你已经有数组中的值。

循环遍历值数组:

for value in "${array[@]}"; do
    # Use "$value" here.
done

或者,使用原始数据数组fields

for column in 2 3 4; do
    value=${fields[column-1]}
    # Use "$value" here.
done

答案4

bash当您不引用参数扩展或命令替换或$(<...)算术扩展时,就会发生分裂。

所以在这里:

IFS='|'                # split on | instead of the default of SPC|TAB|NL

set -o noglob          # disable globbing which is another side effect of leaving
                       # expansions unquoted

set -- $(<file.data)'' # do the splitting. The extra '' is so that
                       # a|b| is split into "a", "b" and "" for instance.
                       # also note that it splits an empty string into one empty
                       # element.

array=("$2" "$3" "$4")

相关内容