When looking at the content of files, I'd like to automatically cat
short files but less
those that exceed the screen size. I could use something with wc -l
, but is there a better way that maybe also considers the window size / current amount of lines available?
2 Answers
Maybe 'less -F file_to_read' is the option : it exits less if the window is sufficient to display all the file, and wait on the pager if it is not the case
-
sounds good, but that does not output anything in that case, and the exit codes is the same in both cases Jun 22, 2012 at 9:53
-
I just try 'less -F /etc/passwd' and it display the file correctely (with or without pager). You are right, the return code is 0 in both cases.– DomJun 22, 2012 at 10:44
-
12That command works as requested, but with a minor glitch: it clears the screen after displaying the file. Adding the
-X
option will stop the clearing, so short files will be displayed likecat
does. Unfortunately with-X
the screen will not be cleared neither after displaying long, scrolled files. Jun 22, 2012 at 11:12 -
1@manatwork that's great, thanks. Not clearing the screen is actually ok, since that's what would (not) happen if
cat
were called as well Jun 22, 2012 at 11:50
To give you the formula which involves the wc
-based check:
(($(wc -l<input_file)<=$(tput lines))) && echo 'will fit' || echo 'not enough'
There is a $LINES
shell variable which can also be used:
(($(wc -l<input_file)<=LINES)) && echo 'will fit' || echo 'not enough'
But $LINES
is updated only when at the command prompt. To understand what I mean, run this and resize the terminal window during the sleep
:
( sleep 3; echo $LINES; tput lines )
-
Thanks, this has the advantage that it can be tuned to use
less
already if e.g. 2/3 of the screen were used bycat
. Jun 22, 2012 at 11:57
git log
which does this exact thing. You never know in advance what you're going to get (do you have to hitq
?).cat
to view files. Typically you should only usecat
to send the contents of a file to stdout so it can be piped to another process. The reason to avoid usingcat
for viewing is that it sends the raw bytes to the terminal, which can cause unexpected terminal commands to be executed (e.g., some users have gotten stuck when a file happened to contain the right bytes to disable the terminal keyboard). You should usually use a pager likeless
or an editor, which will format special characters for display so they aren't interpreted by the terminal.cat -v
so it escapes special characters.cat
ing possible? which might be a better solutioncat -v
out