arrays - 在 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
}
将文本作为数组读取不起作用。
解决方案
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.
推荐阅读
- jquery - CSS过渡高度属性不起作用
- python - 是否可以在从 list 函数中检索文件列表信息的同时使用 Python ftplib 下载文件?
- android - Camera1 API中的前后摄像头之间快速翻转?
- php - PHPMailer - 仅在 smtpdebug 中输出服务器连接?
- django - 在 DjangoRestFramework 中,是否期望忽略 MultipleChoiceField 默认属性?
- python - 请问如何优化这个 Python 代码?
- python - 如何在python中用大写单词分割字符串而不用前面的空格
- python - 我在尝试通过 sqlalchemy 连接到远程 postgreSQL 服务器时遇到操作错误,如下所述
- python - 如何将熊猫数据框中的所有行与特定列的相同值合并?
- r - 在多列上使用 ifelse 条件