Read tab-separated file line into array

前端 未结 3 967
情话喂你
情话喂你 2020-11-30 19:06

I would like to read a file into a script, line by line. Each line in the file is multiple values separated by a tab, I\'d like to read each line into an array.

Typ

相关标签:
3条回答
  • 2020-11-30 19:17

    You could also try,

    OIFS=$IFS;
    IFS="\t";
    
    animals=`cat animals.txt`
    animalArray=$animals;
    
    for animal in $animalArray
    do
        echo $animal
    done
    
    IFS=$OIFS;
    
    0 讨论(0)
  • 2020-11-30 19:33

    You're very close:

    while IFS=$'\t' read -r -a myArray
    do
     echo "${myArray[0]}"
     echo "${myArray[1]}"
     echo "${myArray[2]}"
    done < myfile
    

    (The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

    0 讨论(0)
  • 2020-11-30 19:33

    If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

    while IFS=$'\t' read -r column1 column2 column3 ; do
      printf "%b\n" "column1<${column1}>"
      printf "%b\n" "column2<${column2}>"
      printf "%b\n" "column3<${column3}>"
    done < "myfile"
    

    to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

    0 讨论(0)
提交回复
热议问题