1

Imagine you would want less to auto scroll to the end. Easy, as its manual states, do less +G.

Imagine you would want less to start at the beginning but after soaking its whole input. Easy, do less +Gg (to the end then back to the beginning), it supports several command chaining. Don't you believe? Chain Gg sequences enough, and you will end up watching less go back and forth.

Imagine you would want less to advance to the sixth occurrence of the == sequence. Can't use less +/==nnnnn! That searches ==nnnnn, instead of searching == and then searching next five times. What to do now?

174140
  • 94
  • 2
  • 13
  • 33
  • Use cat or grep? – Seth Aug 01 '19 at 09:22
  • Grep then More is a reasonable alternative, as it is just hitting the N key five times. However [multiple separate commands](https://superuser.com/a/1466515/174140) just working is perfect. – 174140 Aug 01 '19 at 12:23

3 Answers3

3

Imagine you could, in fact, specify multiple separate commands like this:

less +/== +nnnnn


 

If that hadn't worked, you could embed a literal newline in the parameter:

less $'+/==\nnnnnn'
less "+/==
nnnnn"
u1686_grawity
  • 426,297
  • 64
  • 894
  • 966
  • All of those totally make sense. I don't know why, I can't run any of the three in my Konsole unless inside a nested Tmux organizer, nor in `tty1` to `tty6` unless inside a nested Tmux organizer. This is Debian GNU/Linux stretch 9.9 in `lsb_release -a`. – 174140 Aug 01 '19 at 12:20
  • Compare `type less` and `printenv LESS` in both. – u1686_grawity Aug 01 '19 at 12:25
  • `less is /usr/bin/less` in all three of: `tty1` to `tty6`, inside Tmux, and in Konsole; in all three cases `printenv LESS` does not show anything, returning an exit status code of 1. – 174140 Aug 01 '19 at 16:37
0

This method uses awk to find the line number of the string and uses it as parameter to less:

less +$(awk '/==/{++n; if (n==6) { print NR; exit}}' file) file

This was inspired by the Stack Overflow post shell script to find the nth occurrence of a string and print the line number, where are found more methods for finding the line number.

For ease of use, this command can be embedded in a bash function with the file, string and occurrence number as parameters.

harrymc
  • 455,459
  • 31
  • 526
  • 924
0

In brief

For this purpose I did a function

Myless(){ less +g$(grep -n -m$2 "$1" "$3"  | cut -f1 -d: | tail -n 1) "$3"; }

then I call as

Myless == 6 myfile

Asking to grep to find the pattern, print the linenumber, -n, stop after the m-th occurence -m$2, cutting the number cut -f d:, taking the last one tail -n 1`...

It can be optimized (for very large files) searching for the byte as a binary data and then pointing less to that byte...

... or it can be used sed in a more compact way to extract the linenumber (sed -n '/pattern/=' myfile)...

Hastur
  • 18,764
  • 9
  • 52
  • 95