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
  • 134

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"
grawity
  • 501,077
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
  • 498,455
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
  • 19,483
  • 9
  • 55
  • 99