I would like to display as much from a file as possible which still fits in the terminal window, i.e. like a head with a dynamic number of lines.

If there are no lines which wrap to multiple lines and the prompt takes a single line then I can achieve that with head -n $(($(tput lines)-1)).

Is there a solution that doesn't require the assumptions above?

Edit: The solution should be non-interactive, so e.g. less doesn't work as far as I know.

Edit2: The solution should preferably also handle properly non-printing characters like ANSI escape sequences for text coloring.


You can wrap with fold, then head it:

onepage () {
  fold -w "$(tput cols)" -s "$@" |
    head -n "$(($(tput lines)-1))"

Or maybe use pr. Assuming GNU pr:

pr -l "$((LINES - 1))" +1:1 -t
  • -l ... - set page height to $LINES - 1.
  • +1:1 start printing from the first page ... till the first page.
  • -t - don't print the header.
  • The first solution using fold and head works nicely expect when prompt is using more than one line. Is there a way to determine that from e.g. $PS1? The pr solution didn't work properly with lines which wrap to multiple lines. – Samuli Asmala Jul 8 at 9:38
  • @SamuliAsmala not without expanding PS1 the way the shell expands it completely. If in bash, you could do something like foo=${PS1@P}; echo ${#foo} to get the length of the prompt, and then compare it with the width to see if it goes to multiple lines. (or maybe count lines in the expanded prompt) – muru Jul 8 at 9:52
  • Your example doesn't work since I'm using .bash-git-prompt and my prompt is a bit more complicated: \[\033[0;32m\]✔\[\033[0;0m\] \[\033[0;33m\]\w\[\033[0;0m\] [\[\033[0;35m\]${GIT_BRANCH}\[\033[0;0m\] ↑·2\[\033[0;0m\]|\[\033[0;34m\]✚ 1\[\033[0;0m\]\[\033[1;34m\]⚑ 2\[\033[0;0m\]\[\033[0;0m\]] \n\[\033[0;37m\]$(date +%H:%M)\[\033[0;0m\] $ – Samuli Asmala Jul 8 at 13:52
  • I also noticed that the fold solution doesn't work if there are non-printing characters like ANSI escape sequences for text coloring. There is a related question about Wrap text accounting for non-printing characters which is still unanswered. – Samuli Asmala Jul 8 at 13:57

Perhaps use the program less

In the terminal, type:

less nameOfTheTextFile

And it will show all available lines that fit, starting from the first line of the text file

  • 1
    less is interactive and doesn't return immediately back to prompt so unless there is a way to change that this method doesn't fit my needs. I've updated the question to be more clear on this. – Samuli Asmala Jul 8 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.