How to read the file content into a variable in one go?

后端 未结 3 1816
甜味超标
甜味超标 2021-01-31 03:22

In Java, if you know for certain a file is very small, you can use readBytes() method to read the content in one go instead of read it line by line or using buffer.

相关标签:
3条回答
  • 2021-01-31 04:01

    Process the lines inside the loop instead of after it. If you really need the file in a variable:

    var=$(<file)
    
    0 讨论(0)
  • 2021-01-31 04:01

    Another alternative is to use the nice mapfile builtin:

    mapfile < test.file
    echo "${MAPFILE[@]}"
    
    0 讨论(0)
  • 2021-01-31 04:05

    As another option, you can build an array of lines. If you're running bash 4+, you can use the mapfile builtin:

    mapfile -t lines <test.file
    

    If you want the lines to be output as well as stored you could do something like this:

    mapfile -t lines < <(tee /dev/tty <test.file)
    

    Then "${lines[0]}" will be the first line of the file, "${lines[1]}" the second, and so on. ${#lines[@]} will be the number of lines; "${lines[@]}" will be the whole array, while "${lines[*]}" will be the lines joined together with spaces into one big string.

    For older versions of bash, you can build the array manually:

    lines=()
    while IFS= read -r line
    do
      printf '%s\n' "$line"
      lines+=("$line")
    done < test.file
    
    0 讨论(0)
提交回复
热议问题