`less` "search backward" command line switch?

2

1

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

ultracrepidarian

Posted 2017-12-21T18:57:35.933

Reputation: 179

Answers

3

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

davidmneedham

Posted 2017-12-21T18:57:35.933

Reputation: 1 724

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 – 2017-12-21T20:10:31.817

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 – 2017-12-21T20:22:01.313

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 – 2017-12-21T20:33:42.277

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 – 2017-12-21T20:36:26.707

It does nothing on mine. $LESS is not set. – ultracrepidarian – 2017-12-21T20:52:07.557

Got it. Something to do with bash expansion probably. It works when the command is quoted: less +'?cd' .bash_history. – ultracrepidarian – 2017-12-21T21:00:28.847