以下是一个实现示例:

#!/bin/bash

# 将文件名作为参数传入脚本
filename=$1

# 初始化计数器和输出文件名
count=0
output_file=""

# 逐行读取文件
while read line; do
  # 如果当前行是空行,则将计数器加一
  if [[ -z "$line" ]]; then
    ((count++))
    output_file=""
  # 如果当前行包含特定字符串,则创建新的输出文件并将当前行写入其中
  elif [[ "$line" == *"特定字符串"* ]]; then
    ((count++))
    output_file="output_$count.txt"
    echo "$line" > "$output_file"
  # 如果当前行不是空行也不包含特定字符串,则将当前行写入当前输出文件
  else
    if [[ -n "$output_file" ]]; then
      echo "$line" >> "$output_file"
    fi
  fi
done < "$filename"

在上面的示例中,我们使用了一个 while 循环来逐行读取文件。当读取到空行时,我们将计数器加一并将输出文件名重置为空字符串。当读取到包含特定字符串的行时,我们创建一个新的输出文件并将当前行写入其中。最后,如果读取到的行不是空行也不包含特定字符串,我们将当前行写入当前输出文件中。

linux shell中以空行分割文件 当第一行有匹配的字符串时 将其输出到单独的文件中

原文地址: http://www.cveoy.top/t/topic/bXq7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录