6

I know less +/pattern filename will open the file and navigate to the first occurrence of the pattern. Is there a way to tell less to search from the end backwards? Does it even accept more than one + switch?

Do not work:

less +?pattern filename
less +G +?pattern filename
8

The man page for less states the syntax is less +?pattern filename

?pattern
       Search  backward  in  the  file for the N-th line containing the
       pattern.  The search starts at the last line displayed (but  see
       the -a and -j options, which change this).

Press n to continue to search for the pattern backwards. Press N to search for the pattern forwards.

Example

For testfile.txt of

apple
banana
carrot
apple
banana
carrot
apple
banana
carrot

less +?banana testfile.txt shows the following:

banana
carrot
6
  • 1
    The man page does not state so explicitly, and the syntax you provided does not lead to the desired result. It works, in a sense that the same thing happens as if you were to open the file and try searching backwards - you get "Pattern not found". Backward search does not jump to the end of the file when you are on the first line of the file. Hence, I tried less +G +?pattern filename, but then again, reading the man page, it appears that only one +cmd is allowed. So, it appears that there is no way to achieve what I'm looking for. – ultracrepidarian Dec 21 '17 at 20:10
  • I do not understand what you want to do. Can you provide an example? The syntax I provided above looks for a term starting at the last line of the file and searches upwards. – davidmneedham Dec 21 '17 at 20:22
  • Try less +/cd .bash_history vs. less +?cd .bash_history. The first example opens the file and navigates to the first occurrence of cd in your bash history (hopefully you have them). The second example does nothing, except open the file, as if it's less .bash_history. – ultracrepidarian Dec 21 '17 at 20:33
  • less +?cd .bash_history on my system shows the latest occurrence of cd in my bash history. Perhaps you have the LESS environmental variable set in a way that is overriding what I'm expecting? – davidmneedham Dec 21 '17 at 20:36
  • It does nothing on mine. $LESS is not set. – ultracrepidarian Dec 21 '17 at 20:52
0

In general it is better to escape ? and the pattern from the shell like this:

less '+?pattern' filename

In your case you might not get what you expect when e.g. there is a file matching +?pattern or you have set bash option nullglob (use shopt nullglob to check it).

In doubt, you can use echo to look what your shell changed:

echo less +?pattern filename

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.