根据终端的长度计算换行后的行数 [英] Count number of lines after wrapped by terminal’s length
问题描述
假设您的tput cols
(或COLUMNS
)等于100
,并且您有一个纯文本文件foo.txt
,其中一行的行长为120个字符.
Suppose your tput cols
(or COLUMNS
) is equal to 100
and you have a plain text file foo.txt
with a single line that is 120 characters long.
如果您想计算其中包含的行数,可以执行cat foo.txt | wc -l
,并且不足为奇,输出大概是1
.
If you wanted to count number of lines it contains you could do cat foo.txt | wc -l
and unsurprisingly enough the output would presumably be 1
.
但是,如果您使用less
之类的分页器(例如less foo.txt
)打开文件,则您的眼睛实际上会看到的是两行(AFAIK,除非您不说--chop-long-lines
,less
将包裹"比您的终端机宽度更长的线).
But if you’d open the file with a pager, such as less
, like less foo.txt
then what your eyes would actually see are two lines instead (AFAIK, unless you don’t say --chop-long-lines
, less
will "wrap" lines that are longer than your terminal’s width).
同样,如果尝试使用less
(如less --LINE-NUMBERS foo.txt
)查看行号,则输出将类似于:
Again, if you’d try to see line numbers, using less
, like less --LINE-NUMBERS foo.txt
, than the output would be something like:
1 something something...
1 more stuff
基本上less
意识到" foo.txt
中的唯一一行比终端的宽度长,因此它将包裹"以可视化,但是会告诉您实际上您看到的第一行和第二行实际上与foo.txt
中的第一行相同.
Basically less
is "aware" that the only line in foo.txt
is longer than your terminal’s width, so it will "wrap" it to visualize, but will tell you that actually first and the second lines that you see are actually the same line #1 in foo.txt
.
所以,我的问题是:在包裹后(眼所见的行数),而不是行数,您如何计算"(例如,用bash表示)行数?文件实际上包含什么? (在上述情况下,该数字将是2
而不是1
.)
So, my question is: how could you "calculate" (say, in bash) number of lines after wrapping (number of lines that your eyes see), rather than number of lines that the file actually contains? (In scenario above, the number would be 2
instead of 1
.)
推荐答案
实际上,有一个更好的解决方案:
Actually, there is a better solution:
fold -w "$COLUMNS" testfile | wc -l
fold
命令会将文件包装到给定的列数,并且可以作为GNU coreutils的一部分广泛使用.
The fold
command will wrap a file to a given column count and is widely available as part of the GNU coreutils.
这篇关于根据终端的长度计算换行后的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!