Search code examples
bashwc

Count number of lines after wrapped by terminal’s length


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.

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.

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).

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

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.

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.)


Solution

  • Actually, there is a better solution:

    fold -w "$COLUMNS" testfile | wc -l
    

    The fold command will wrap a file to a given column count and is widely available as part of the GNU coreutils.