You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash文本文件句子按行拆分方案咨询(用于句子长度统计)

Bash实现英文句子拆分与长度统计

你之前用tr替换句点成换行的方法存在两个问题:会丢失句末标点,且无法覆盖问号、感叹号结尾的句子。可以用sed实现精准的句子拆分,同时保留标点,再结合循环统计长度。

完整脚本

#!/bin/bash

FILE="NameOfFile"

# 拆分句子并过滤空行,再逐行处理
sed -E 's/([.?!]) +/\1\n/g' "$FILE" | sed '/^$/d' | while read -r sentence; do
    # 计算当前句子的长度(包含句末标点)
    sentence_length=${#sentence}
    echo "句子内容:$sentence"
    echo "句子长度:$sentence_length"
    echo "------------------------"
done

关键步骤解释

  1. 句子拆分(第一个sed命令)
    sed -E 's/([.?!]) +/\1\n/g'

    • -E 启用扩展正则,简化正则写法
    • ([.?!]) 捕获所有常见的句末标点(句号、问号、感叹号)
    • + 匹配标点后连续的空格(适配句子间的空格分隔)
    • \1\n 把捕获的标点原样保留,后面加换行符,实现句子拆分
  2. 过滤空行(第二个sed命令)
    sed '/^$/d'
    处理后可能出现空行(比如原文件的空行),用这个命令删除,避免循环读取无效内容

  3. 长度统计
    在循环里用${#sentence}直接获取当前句子的字符长度,包含句末标点和空格

效果验证

针对你提供的初始文本:

SMS marketing is an excellent customer service tool because messages are delivered and read almost immediately — and there’s room for two-way communication. And SMS customer service can be scaled and automated. Plus, if you leverage this channel, your business will save money on phone service and customer service personnel training.

See a few templates for customer support messages below.

处理后会输出:

句子内容:SMS marketing is an excellent customer service tool because messages are delivered and read almost immediately — and there’s room for two-way communication.
句子长度:137
------------------------
句子内容:And SMS customer service can be scaled and automated.
句子长度:53
------------------------
句子内容:Plus, if you leverage this channel, your business will save money on phone service and customer service personnel training.
句子长度:104
------------------------
句子内容:See a few templates for customer support messages below.
句子长度:56
------------------------

内容的提问来源于stack exchange,提问作者Facundo Ferreira da Camara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:21:43