首页 > 解决方案 > 在 Bash 中返回给定宽度的文本段落所需的行数

问题描述

给定一个宽度,我试图计算一个包含段落(\n 行结尾)的文本块需要多少行。

我不能简单地将字符数除以宽度,因为行尾会提前创建新行。我不能只计算行尾,因为有些段落会换行。

我认为我需要遍历段落,将字符除以每个字符的宽度并将结果加在一起。

    count_lines() {
    TEXT="$(echo -e $1)"
    WIDTH=$2
    LINES=0
    for i in "${TEXT[@]}"
    do
    PAR=$(echo -e "$i" | wc -c)
    LINES=$LINES + (( $PAR / $WIDTH ))
    done
    RETURN $LINES
}

将文本作为数组读取不起作用。

标签: arraysstringbashshell

解决方案


count_lines() {
  fmt -w "$2" <<<"$1" | wc -l
}
  • fmt是一个长期存在的(早在 Plan 9,并且是 GNU 系统上 coreutils 的一部分)的 UNIX 工具,它可以将文本包装到所需的宽度。
  • <<<是 herestring 语法,是 heredocs 的 ksh 和 bash 替代方案,允许在不将脚本拆分为多行的情况下使用它们。

测试这个:

text=$(cat <<'EOF'
This is a sample document with multiple paragraphs. This paragraph is the first one.

This is the second paragraph of the sample document.
EOF
)
count_lines "$text" 20

...返回 . 的输出10。这是正确的,因为文本换行如下(为了便于阅读,在开头添加了行):

 1 This is a
 2 sample document
 3 with multiple
 4 paragraphs. This
 5 paragraph is the
 6 first one.
 7 
 8 This is the second
 9 paragraph of the
10 sample document.

推荐阅读