From a script, I want to invoke less
on a file and have it print the output to the console, rather than a new screen. If the file is short enough to fit on one screen, I want to disable scrolling. If it's longer than one screen, I want to be able to scroll through it, but once I hit the bottom, I want less
to return control to the console. Lines should also be chopped (it's okay to lose the end of the strings past the console window in this case).
I also would like it to highlight a certain pattern.
Here is what I'm using for arguments:
less -SFXE -p "ccc" fileToShow.txt
I use -S
to chop long lines, -FX
to detect if the file has less lines than the console and print all the text to the console without scrolling, and -E
to quit less
when I've reached the end of the file, for the cases when the text is longer than the console and I need scrolling.
These work well until I add the -p
switch for highlighting matches.
Suppose fileToShow.txt contains this:
aaa
bbb
ccc
ddd
eee
Without the pattern switch, I get this:
[evan@localhost] $ less -SFXE fileToShow.txt
aaa
bbb
ccc
ddd
eee
[evan@localhost] $
When I add the pattern matching, less prints out the empty lines up to the console height (using tildes to show the empty lines).
[evan@localhost] $ less -SFXE -p "ccc" fileToShow.txt
ccc
ddd
eee
~
~
~
~
~
~
~
~
[evan@localhost] $
Is there any way to use the -p
switch and not have it show those empty lines when using -F
? (Note: the "ccc" line is highlighted as desired, I just have this unintended side effect.)
My shell is bash 3.2.25
and my less version is 436
. OS is RHEL.
-p
not only searches and highlights patterns, but also moves the cursor to the first match. I think that the cursor moving part is what causesless
to show those empty lines. Is there a way to get the highlighting without moving the cursor?grep --color=always -E "^|$2" "$1"|less -SFXER
, where$1
is the file name and$2
is the search pattern. Not exactly neat, but some sort of answer. Note that this would list all the lines, highlighting the pattern, whereasless -p
omits lines ahead of the first match: to do this you would need to usesed
.