Unix tip: Making do with less

The head, tail and more commands are among the first ten or twenty commands that most beginning Unix users are going to learn. A far more intriguing command for many of the tasks they will end up using these commands for is the seemingly modest, but far more versatile, less.

The name "less" is obviously something of a spoof, meant to contrast the less command with the more familiar more. It's versatility, however, has converted a lot of Unix users to exclusive use of less.

Less allows you view files and, at the same time, do basic find operations. Unlike more, it allows you to search both forwards and backwards for your search string.

To open a file using less, type the less command followed by the file name. You can search for text with vi commands such as / (look forward) and ? (look backward). You can page down with f (forward) and up with b (backward). You can move up or down one line at a time with e (down one) or y (up one) or with the more obvious up and down arrows that I much prefer. Alternately, you can use the Enter key to move down one line at a time as you would with more.

Less also allows you to move ahead or back a page at a time using the space bar (ahead) or pressing "b" (back). Pressing h brings up a help screen with a summary of less commands. As in vi, you can move to the top of the file with g and the bottom with G. Your left and right arrow keys will move you one character at a time to the left or right within your text.

The n (next) command will repeat your command as it does in vi. Typing N will bring up your previous match.

Less also adjusts to the size of your window. Displaying a log file in an 80 columns window with lines wrapped around when you prefer to see them one line per screen line? No problem, just stretch your window! The text will adjust itself before your eyes. Or, if you prefer, use your left and right arrows to move to the left and the right within your text.

And this is just scratching the surface! Take a look at the help menu and you'll see there's a lot more to this little command than you'd expect.

And here's one idea you might not have thought of. If you need to look at a log file, such as syslog or messages, you are most likely going to be more interested in the more recent lines. So, you are likely to use the tail command. If you then need to see a little more, you might issue a second tail command, giving it an argument such as -50. A more effective way to do this might be to use the less command, then jump down to the very bottom of the file with a shift-g sequence. From there, you back scroll back up in the file indefinitely (well, at least up to the top of the file). Enter q to exit.

This article is published as part of the IDG Contributor Network. Want to Join?

Computerworld's IT Salary Survey 2017 results
Shop Tech Products at Amazon