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?
Asked
Active
Viewed 1,912 times
12
rahmu
- 20,023
Tobias Kienzler
- 9,374
2 Answers
20
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
Dom
- 948
-
sounds good, but that does not output anything in that case, and the exit codes is the same in both cases – Tobias Kienzler Jun 22 '12 at 09: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. – Dom Jun 22 '12 at 10:44
-
12That command works as requested, but with a minor glitch: it clears the screen after displaying the file. Adding the
-Xoption will stop the clearing, so short files will be displayed likecatdoes. Unfortunately with-Xthe screen will not be cleared neither after displaying long, scrolled files. – manatwork Jun 22 '12 at 11:12 -
1@manatwork that's great, thanks. Not clearing the screen is actually ok, since that's what would (not) happen if
catwere called as well – Tobias Kienzler Jun 22 '12 at 11:50
9
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 )
manatwork
- 31,277
-
Thanks, this has the advantage that it can be tuned to use
lessalready if e.g. 2/3 of the screen were used bycat. – Tobias Kienzler Jun 22 '12 at 11:57
git logwhich does this exact thing. You never know in advance what you're going to get (do you have to hitq?). – bitmask Jun 22 '12 at 19:47catto view files. Typically you should only usecatto send the contents of a file to stdout so it can be piped to another process. The reason to avoid usingcatfor 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 likelessor an editor, which will format special characters for display so they aren't interpreted by the terminal. – Chris Page Jun 25 '12 at 06:25cat -vso it escapes special characters. – Chris Page Jun 25 '12 at 06:26cating possible? which might be a better solution – Tobias Kienzler Jun 25 '12 at 08:15cat -vout – Tobias Kienzler Jun 25 '12 at 08:16