Tricks with less
less is one of those utilities I use day in and day out, and it’s easy to forget that it has some really powerful features.
Nine times out of ten, I
less a file and then start finding lines using the
/ command. You can make this case-insentive if you enter
-I and hit return - you’ll see a prompt saying
Ignore case in searches and in patterns (press RETURN)
Then when you search using
? you can be confident that you won’t miss something due to case sensitivity.
Even more useful is filtering; you can strip out all the lines you don’t care about by typing
& - you’ll get a
&/ prompt where you can enter your filter text. Say you have an nginx access log:
18.104.22.168 - - [02/Mar/2021:05:15:07 -0800] "GET /2021/01/04/hello-2021 HTTP/1.1" 200 7073 "https://jay.gooby.org/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.18 Safari/537.36" 22.214.171.124 - - [02/Mar/2021:05:15:33 -0800] "HEAD / HTTP/2.0" 200 390 "https://t.co/Pp644lxwd6" "-" 126.96.36.199 - - [02/Mar/2021:05:16:16 -0800] "GET /feed.xml HTTP/1.1" 200 13370 "-" "Feedbin feed-id:2056147 - 2 subscribers" 188.8.131.52 - - [02/Mar/2021:05:24:34 -0800] "GET /robots.txt HTTP/1.1" 200 4785 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)" 184.108.40.206 - - [02/Mar/2021:05:26:56 -0800] "GET /feed.xml HTTP/1.1" 200 13370 "-" "Feedbin feed-id:2056147 - 2 subscribers" 220.127.116.11 - - [02/Mar/2021:05:29:23 -0800] "GET / HTTP/1.1" 200 7706 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
You can hide anything that isn’t a HEAD request by typing
& and then at the
&/ prompt enter
18.104.22.168 - - [02/Mar/2021:05:15:33 -0800] "HEAD / HTTP/2.0" 200 390 "https://t.co/Pp644lxwd6" "-"
less +F as a replacement for
How many times have you been tailing a file with
tail -f and then wanted to search for something, so you end up quitting the tail and then
lessing it instead? I used to do this all the time, until I discovered that
less has a tail mode. Use it like this:
less +F /some/file
You can ctrl-c to exit the tailing mode and then use all the above tricks to filter and search, and then when you’re done, press shift-f to go back to tail mode.
All links, in order of mention:
- less: https://linux.die.net/man/1/less
- really powerful features: https://unix.stackexchange.com/questions/31/list-of-useful-less-functions