How to read variables from file, with multiple variables per line?

前端 未结 2 936
心在旅途
心在旅途 2021-01-03 17:10

I\'m trying to read from a file, that has multiple lines, each with 3 informations I want to assign to the variables and work with.

I figured out, how to simply disp

相关标签:
2条回答
  • 2021-01-03 17:37

    The below assumes that your desired result is the set of assignments a=1, b=2, and c=3, taking the values from the first line and the keys from the second.


    The easy way to do this is to read your keys and values into two separate arrays. Then you can iterate only once, referring to the items at each position within those arrays.

    #!/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]}"
    

    See:

    • BashFAQ #6 - How can I use variable variables (indirect variables, pointers, references) or associative arrays?
    • The bash-hackers page on the read builtin, documenting use of -a to read words into an array.
    0 讨论(0)
  • 2021-01-03 17:38

    I think all you're looking for is to read multiple variables per line: the read command can assign words to variables by itself.

    while read -r first second third; do
        do_stuff_with "$first"
        do_stuff_with "$second"
        do_stuff_with "$third"
    done < ./test.txt
    
    0 讨论(0)
提交回复
热议问题