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

后端 未结 3 1820
甜味超标
甜味超标 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: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 

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

    mapfile -t lines < <(tee /dev/tty 

    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
    

提交回复
热议问题