【问题标题】:How to read variables from file, with multiple variables per line?如何从文件中读取变量,每行有多个变量?
【发布时间】:2018-09-29 01:56:31
【问题描述】:

我正在尝试从一个文件中读取,该文件有多行,每行都有 3 个我想分配给变量并使用的信息。

我知道如何在终端上简单地显示它们,但不知道如何将它们实际分配给变量。

while read i
do
  for j in $i
  do
    echo $j
  done
done < ./test.txt

test.txt:

1 2 3
a b c

所以我想读取外循环中的行,然后分配 3 个变量,然后使用它们,然后再转到下一行。

我猜我必须在没有内部循环的情况下读取行的值,但我现在无法弄清楚。

希望有人能指出正确的方向。

【问题讨论】:

标签: bash shell


【解决方案1】:

下面假设您想​​要的结果是一组赋值 a=1b=2c=3,取第一行的值和第二行的键。


执行此操作的简单方法是将键和值读入两个单独的数组。然后你可以只迭代一次,引用这些数组中每个位置的项目。

#!/usr/bin/env bash
case $BASH_VERSION in
  ''|[123].*) echo "ERROR: This script requires bash 4.0 or newer" >&2; exit 1;;
esac

input_file=${1:-test.txt}

# create an associative array in which to store your variables read from a file
declare -A vars=( )

{
  read -r -a vals               # read first line into array "vals"
  read -r -a keys               # read second line into array "keys"
  for idx in "${!keys[@]}"; do  # iterate over array indexes (starting at 0)
    key=${keys[$idx]}           # extract key at that index
    val=${vals[$idx]}           # extract value at that index
    vars[$key]=$val             # assign the value to the key inside the associative array
  done
} < "$input_file"

# print for debugging
declare -p vars >&2

echo "Value of variable a is ${vars[a]}"

见:

【讨论】:

    【解决方案2】:

    我认为您正在寻找的只是每行读取多个变量:read 命令可以自行将单词分配给变量。

    while read -r first second third; do
        do_stuff_with "$first"
        do_stuff_with "$second"
        do_stuff_with "$third"
    done < ./test.txt
    

    【讨论】:

    • 嘿。我让 OP 想要 a=1、b=2、c=3,但这似乎是过度阅读。
    猜你喜欢
    • 2013-03-15
    • 2016-09-14
    • 2022-10-17
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多