5

Consider the following file:

$ LESS= \less test
abc
def
abc

By default, searching /abc in less will jump to line 3 since /pattern search starts at second line according to man 1 less:

/pattern
       [... snipped ...]  The search starts at the second line displayed (but see the 
       -a and -j options, which change this).

-a and -j do not help.

It's annoying that I have to do a backward search (N) after each /pattern search to make sure I have not missed anything important in the first line.

How do I make less pattern search starts at first line displayed?

Edit:

less version:

$ less --version
less 436
Copyright (C) 1984-2009 Mark Nudelman

less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
  • 2
    Funny; the docs for my version of less ("less 458 (GNU regular expressions)") says "The search starts at the first line displayed". And it does what it says: If I go the top and search /LESS, it stays on the top. What's your version of less? I kinda want to make a mental note for this … – The Sidhekin Mar 15 '15 at 17:33
  • @TheSidhekin $ less --version less 436 Copyright (C) 1984-2009 Mark Nudelman from Debian squeeze-lts – cychoi Mar 15 '15 at 21:59
2

The most straightforward solution is to upgrade to less 441 or newer. From the changelog:

less-440 fixes a bug in less-438 and, at the risk of some feature creep, adds one much requested feature. The -A option changes search behavior so that an initial search includes the entire displayed screen and does not skip the first line as is currently done. Non-initial searches (for example, the "n" command) continue to skip the first (target) line to allow searches to proceed past the current screen.

less-441 changes the search behavior so that the new -A option introduced in less-440 is now the default. The -A option now changes the behavior to the old, pre-440, behavior.

The -a and -j option can cause the search to begin further than the topmost screen line, but I don't think they can cause the search to begin at the topmost screen line — that's why the -A option was added (and made the default, apparently it was very popular).

1

The best workaround I could come up with is using the "KEEP current position" feature to highlight the matched text but do not jump to target line:

/CTRL+Kpattern

However, it incurs additional keystrokes.

edit:

The issue has been fixed in newer version of less. Refer to @Gilles's answer for details.

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.