Bash while 循环读取行 upto ;

Bash while loop to read line upto ;

我有一个像

这样的文本文件
line2
line3;
line4
line5
line6
line7;

我需要一个循环来读取每一行直到 ;。 在第一个循环中读取到第 3 行;在第二个循环中直到第 7 行;等等。 无需将行合并为一个行

您可以使用两个循环:一个继续直到文件末尾,另一个内部循环读取单独的行,直到找到以 ;.

结尾的行

例如,

while :; do
    lines=()
    while IFS= read -r line; do
        lines+=( "$line" )
        if [[ $line = *; ]]; then
            break
        fi
    done
    if (( ${#lines[@]} == 0 )); then
        # The previous loop didn't add anything to the array,
        # so the last read must have failed, and we've reached
        # then end of the file
        break
    done
    # do something with $lines
done < file.txt
    

或者,使用一个循环,在找到以 ; 结尾的行时暂停使用行:

lines=()
while IFS= read -r line; do
    lines+=("$line")
    if [[ $line = *; ]]; then
        # do stuff with lines, then clear the array
        lines=()
    fi
done < file.txt

# If applicable, do something with the last batch of lines
# if the file doesn't end with a ;-terminated line.

考虑告诉 read; 而不是换行符处停止,而是使用换行符来分隔单个输入项(当使用 -a 读入数组时,这使每一行成为一个数组元素)。

When given your input,

while IFS=$'\n' read -r -d ';' -a lines; do
  echo "Read group of lines:"
  printf ' - %s\n' "${lines[@]};"
done

...作为输出发出:

Read group of lines:
 - line2
 - line3;
Read group of lines:
 - line4
 - line5
 - line6
 - line7;

如果您愿意,您可以将 printf 替换为 for line in "${lines[@]}"; do 之类的内容,以创建一个内部循环来对组 one-by-one 中的行进行操作。