Less Scrolling – Horizontal Scrolling in Smaller Increments with Less -S

lessscrolling

I'm using less to parse HTTP access logs. I want to view everything neatly on single lines, so I'm using -S.

The problem I have is that the first third of my terminal window is taken up with metadata that I don't care about. When I use my arrow keys to scroll right, I find that it scrolls past the start of the information that I do care about!

I could just delete the start of each line, but I don't know if I may need that data in the future, and I'd rather not have to maintain separate files or run a script each time I want to view some logs.

Example

This line:

access.log00002:10.0.0.0 – USER_X [07/Nov/2013:16:50:50 +0000] "GET /some/long/URL"

Would scroll to: ng/URL"

Question

Is there a way I can scroll in smaller increments, either by character or by word?

Best Answer

The only horizontal scrolling commands scroll by half a screenful, but you can pass a numeric argument to specify the number of characters, e.g. typing 4 Right scrolls to the right by 4 characters. Less doesn't really have a notion of “current line” and doesn't split a line into words, so there's no way to scroll by a word at a time.

You can define a command that scrolls by a fixed number of characters. For example, if you want Shift+Left and Shift+Right to scroll by 4 characters at a time:

  1. Determine the control sequences that your terminal sends for these key combinations. Terminals send a sequence of bytes that begin with the escape (which can be written \e, \033, ^[ in various contexts) character for function keys and keychords. Press Ctrl+V Shift+Left at a shell prompt: this inserts the escape character literally (you'll see ^[ on the screen) instead of it being processed by your shell, and inserts the rest of the escape sequence. A common setup has Shift+Left and Shift+Right send \eO2D and \eO2C respectively.

  2. Create a file called ~/.lesskey and add the following lines (adjust if your terminal sends different escape sequences):

    #command
    \eO2D noaction 4\e(
    \eO2C noaction 4\e)
    \eOD noaction 40\e(
    \eOC noaction 40\e)
    

    In addition to defining bindings for Shift+arrow, you may want to define bindings for arrow alone, because motion commands reuse the numeric values from the last call. Adjust 40 to your customary terminal width. There doesn't appear to be a way to say “now use the terminal width again, whatever it is at this moment”. A downside of these bindings is that you lose the ability to pass a numeric argument to Left and Right (you can still pass a numeric argument to Esc ( and Esc )).

Then run lesskey, which converts the human-readable ~/.lesskey into a binary file ~/.less that less reads when it starts.

Related Question