Linux Commands – less
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have discussed more command in Linux which is used to paginate a large file into multiple screens.
https://cloudaffaire.com/linux-commands-more/
In this blog post, we will discuss less command in Linux. less command is used for the pagination of a large file. less command is very similar to more command in functionality but provides lots of additional features for example forward and backward movement. less command is also much faster than more command as it does not read the entire file at once but in chucks.
Linux Commands – less:
You can use less command for the pagination of large output. Less command can read form a file and display a paginated content on the screen. You can use less command with a pipe instead of a file as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
########################### ## Linux Commands | less ## ########################### ## Prerequisites: One Unix/Linux/POSIX-compliant operating system with bash shell ##----- ## less ##----- ## less [-[+]aABcCdeEfFgGiIJKLmMnNqQrRsSuUVwWX~] ## [-b space] [-h lines] [-j line] [-k keyfile] ## [-{oO} logfile] [-p pattern] [-P prompt] [-t tag] ## [-T tagsfile] [-x tab,...] [-y lines] [-[z] lines] ## [-# shift] [+[+]cmd] [--] [filename]... ## create a long file with 200 lines > myfile; i=1; while [ $i -le 200 ]; \ do echo "$i" >> myfile; ((i++)); done cat myfile ## displays the content of myfile at once less myfile ## displays one screenful at a time ## enter ==> scroll one line at a time ## space ==> scroll one screenful at a time ## q ==> exit ps -ax | less ## also works with pipe |
When displaying the output, less command also provides an interactive mode where you can execute different commands to interact with the screen and output format. Below is the complete list of all interactive commands that can be issued with less command.
Command | Details |
h H | Display this help. |
q :q Q :Q ZZ | Exit. |
e ^E j ^N CR | * Forward one line (or N lines). |
y ^Y k ^K ^P | * Backward one line (or N lines). |
f ^F ^V SPACE | * Forward one window (or N lines). |
b ^B ESC-v | * Backward one window (or N lines). |
z | * Forward one window (and set window to N). |
w | * Backward one window (and set window to N). |
ESC-SPACE | * Forward one window, but don’t stop at end-of-file. |
d ^D | * Forward one half-window (and set half-window to N). |
u ^U | * Backward one half-window (and set half-window to N). |
ESC-) RightArrow | * Left one half screen width (or N positions). |
ESC-( LeftArrow | * Right one half screen width (or N positions). |
F | Forward forever; like “tail -f”. |
r ^R ^L | Repaint screen. |
R | Repaint screen, discarding buffered input. |
/pattern | * Search forward for (N-th) matching line. |
?pattern | * Search backward for (N-th) matching line. |
n | * Repeat previous search (for N-th occurrence). |
N | * Repeat previous search in reverse direction. |
ESC-n | * Repeat previous search, spanning files. |
ESC-N | * Repeat previous search, reverse dir. & spanning files. |
ESC-u | Undo (toggle) search highlighting. |
&pattern | * Display only matching lines |
g < ESC-< | * Go to first line in file (or line N). |
G > ESC-> | * Go to last line in file (or line N). |
p % | * Go to beginning of file (or N percent into file). |
t | * Go to the (N-th) next tag. |
T | * Go to the (N-th) previous tag. |
{ ( [ | * Find close bracket } ) ]. |
} ) ] | * Find open bracket { ( [. |
ESC-^F <c1> <c2> | * Find close bracket <c2>. |
ESC-^B <c1> <c2> | * Find open bracket <c1> |
m<letter> | Mark the current position with <letter>. |
‘<letter> | Go to a previously marked position. |
” | Go to the previous position. |
^X^X | Same as ‘. |
:e [file] | Examine a new file. |
^X^V | Same as :e. |
:n | * Examine the (N-th) next file from the command line. |
:p | * Examine the (N-th) previous file from the command line. |
😡 | * Examine the first (or N-th) file from the command line. |
:d | Delete the current file from the command line list. |
= ^G :f | Print current file name. |
-<flag> | Toggle a command line option [see OPTIONS below]. |
–<name> | Toggle a command line option, by name. |
_<flag> | Display the setting of a command line option. |
__<name> | Display the setting of an option, by name. |
=+cmd | Execute the less cmd each time a new file is examined. |
!command | Execute the shell command with $SHELL. |
|Xcommand | Pipe file between current pos & mark X to shell command. |
v | Edit the current file with $VISUAL or $EDITOR. |
V | Print version number of “less”. |
Note:
- Commands marked with * may be preceded by a number, N. Notes in parentheses indicate the behavior if N is given. A key preceded by a caret indicates the Ctrl key; thus ^K is ctrl-K.
- Default “window” is the screen height and default “half-window” is half of the screen height.
- A search pattern may be preceded by one or more of: ^N or ! Search for NON-matching lines, ^E or * Search multiple files (pass thru END OF FILE), ^F or @ Start search at FIRST file (for /) or last file (for ?), ^K Highlight matches, but don’t move (KEEP position), ^R Don’t use REGULAR EXPRESSIONS.
- Each “find close bracket” command goes forward to the close bracket matching the (N-th) open bracket in the top line. Each “find open bracket” command goes backward to the open bracket matching the (N-th) close bracket in the bottom line.
- A mark is any upper-case or lower-case letter. Certain marks are predefined: ^ means beginning of the file and $ means end of the file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
less myfile ## enters into the interactive mode ## below are some commands that can be issued in interactive mode ## for a complete list, please refer the above table. ## command => h H (Display this help) ## command => q :q Q :Q ZZ (Exit.) ## command => e ^E j ^N CR (Forward one line) ## command => y ^Y k ^K ^P (Backward one line) ## command => f ^F ^V SPACE (Forward one window) ## command => b ^B ESC-v (Backward one window) ## command => ESC-) RightArrow (Left one half screen width) ## command => ESC-( LeftArrow (Right one half screen width) ## command => /pattern (Search forward for matching line) ## command => ?pattern (Search backward for matching line) ## command => n (Repeat previous search) ## command => N (Repeat previous search in reverse direction) ## command => &pattern (Display only matching lines) ## command => p % (Go to beginning of file) |
By default, forward searches start at the top of the displayed screen and backwards searches start at the bottom of the displayed screen (except for repeated searches invoked by the n or N commands, which start after or before the “target” line respectively). The -a option causes forward searches to instead start at the bottom of the screen and backward searches to start at the top of the screen, thus skipping all lines displayed on the screen.
You can also use less -A or –SEARCH-SKIP-SCREEN options which causes all forward searches (not just non-repeated searches) to start just after the target line, and all backward searches to start just before the target line. Thus, forward searches will skip part of the displayed screen (from the first line up to and including the target line). Similarly, backwards searches will skip the displayed screen from the last line up to and including the target line.
1 2 3 4 5 6 7 8 9 |
## use of -a or -A options less -a myfile ## in the interactive mode type /9 to ## perform a forward search for 9 ## forward search starts from 49 less -A myfile ## in the interactive mode type /9 to ## perform a forward search for 9 ## forward search starts from 9 |
You can use less -bn or –buffers=n options which specifies the amount of buffer space less will use for each file, in units of kilobytes (1024 bytes). By default 64 K of buffer space is used for each file (unless the file is a pipe). The -b option specifies instead that n kilobytes of buffer space should be used for each file. If n is -1, buffer space is unlimited; that is, the entire file can be read into memory.
By default, when data is read from a pipe, buffers are allocated automatically as needed. If a large amount of data is read from the pipe, this can cause a large amount of memory to be allocated. The -B option disables this automatic allocation of buffers for pipes, so that only 64 K (or the amount of space specified by the -b option) is used for the pipe.
Warning: use of -B can result in erroneous display, since only the most recently viewed part of the piped data is kept in memory; any earlier data is lost.
1 2 3 4 5 |
## less -bn or -B options less -b1024 myfile ## 1 MB of buffer space will be allocated ps -ax | less -B ## disables autometic allocation of buffer ## allocates 64 KB as deafult buffer |
You can use less -c or –clear-screen options for full screen repaints to be painted from the top line down. By default, full screen repaints are done by scrolling from the bottom of the screen.
1 2 3 4 5 6 7 8 9 10 11 |
## less -c or --clear-screen option less myfile ## scroll down using space bar ## no ~ is printed for lines after endoffile ## as full screen repaints are done by scrolling ## from the bottom of the screen less -c myfile ## scroll down using space bar ## prints ~ for lines after endofline ## as full screen repaints to be painted ## from the top line down |
You can use less -e or –quit-at-eof options to automatically exit the second time it reaches end-of-file. By default, the only way to exit less is via the “q” command. Use -E or –QUIT-AT-EOF options to automatically exit the first time it reaches end-of-file.
1 2 3 4 5 6 7 8 9 10 11 12 |
## less -e or -E options less myfile ## scroll down using space bar ## does not exit less when you reach eof ## press q to exit less less -e myfile ## scroll down using space bar ## when you reach eof, hit space again ## exit less once you reach eof twice less -E myfile ## scroll down using space bar ## exit less once you reach eof |
You can use -f or –force options to forces non-regular files to be opened. Also suppresses the warning message when a binary file is opened. By default, less will refuse to open non-regular files. Note that some operating systems will not allow directories to be read, even if -f is set.
1 2 3 4 5 6 7 8 9 |
## less -f or --force options mkfifo myfifo ## create a non regular file ps -ax > myfifo less myfifo ## open a new terminal and try to read myfifo ## myfifo is not a regular file less -f myfifo ## display the content of myfifo |
You can use less -F or –quit-if-one-screen options to automatically exit if the entire file can be displayed on the first screen.
1 2 3 4 5 6 7 8 9 10 |
## less -F or --quit-if-one-screen options ## create a small file with 10 lines > mysmfile; i=1; while [ $i -le 10 ]; \ do echo "$i" >> mysmfile; ((i++)); done less mysmfile ## displays 10 lines but does not exit less -F mysmfile ## displays 10 lines and exit rm mysmfile |
You can use less -g or –hilite-search options to highlight only the particular string which was found by the last search command. Normally, less will highlight ALL strings which match the last search command. The -g option changes this behaviour This can cause less to run somewhat faster than the default.
1 2 3 4 5 6 7 |
## less -g or --hilite-search options less myfile ## in the interactive mode type /9 to search 9 ## higlights all lines having 9 like 9, 19, 29 etc. less -g myfile ## in the interactive mode type /9 to search 9 ## highlights only 9 |
You can use less – i option to causes searches to ignore case; that is, uppercase and lowercase are considered identical. This option is ignored if any uppercase letters appear in the search pattern; in other words, if a pattern contains uppercase letters, then that search does not ignore case. To ignore the uppercase letter as well, use less -I option which is similar to -i, but searches ignore case even if the pattern contains uppercase letters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
## less -i or -I options sed -i "100i HELLO" myfile ## inserts HELLO on line no. 100 of myfile sed -i "130i hello" myfile ## inserts hello on line no. 130 of myfile less myfile ## in the interactive mode, type /hello ## finds hello, search is case sensitive less -i myfile ## in the interactive mode, type /hello ## finds both hello and HELLO serach is not case ## sensitive if the search tearm is in lower case ## in the interactive mode, type /HELLO ## finds only HELLO, search is case sensitive if ## search tearm is in upper case less -I myfile ## in the interactive mode, type /HELLO ## finds hello HELLO, search is not case sensitive ## even if the search tearm is in uppercase |
You can use less -jn or –jump-target=n options to specify a line on the screen where the “target” line is to be positioned. The target line is the line specified by any command to search for a pattern, jump to a line number, jump to a file percentage or jump to a tag.
1 2 3 4 5 6 7 8 9 |
## less -jn or --jump-target=n options less myfile ## in the interactive mode, type /9 ## target line is displayed on line no. 9 ## with respect to the screen less -j20 myfile ## in the interactive mode, type /9 ## target line is displayed on line no. 20 ## with respect to the screen |
You can use less -J or –status-column options to display a status column at the left edge of the screen. The status column shows the lines that matched the current search, and any lines that are marked (via the m or M command). The status column is also used if the -w or -W option is in effect.
1 2 3 4 5 |
## less -J or --status-column option less -J myfile ## in the interactive mode, type /9 ## * is desplayed in the left of the screen ## where a match is found |
You can use less -K or –quit-on-intr options which causes less to exit immediately (with status 2) when an interrupt character (usually ^C) is typed. Normally, an interrupt character causes less to stop whatever it is doing and return to its command prompt. Note that use of this option makes it impossible to return to the command prompt from the “F” command.
1 2 3 4 5 6 7 |
## less -K or --quit-on-intr options less myfile ## press control + c ## returns the prompt with bell alert less -K myfile ## press control + c ## exit less with bell alert |
You can use less -m or -M options to prompt verbosely. The -m or –long-prompt option causes less to prompt verbosely (like more), with the percent into the file. The -M or –LONG-PROMPT option causes less to prompt even more verbosely than more.
1 2 3 4 5 6 7 8 9 10 |
## less -m or -M options less myfile ## hit space bar to scroll ## only prompt (:) is returned in the bottom less -m myfile ## hit space bar to scroll ## %of file scrolled is returned in the bottom less -M myfile ## hit space bar to scroll ## more details are returned in the bottom |
You can use less -n or –line-numbers options to suppresses line numbers in the verbose prompt and in the = command.
1 2 3 4 |
## less -n or --line-numbers options less -M myfile ## returns myfile lines 1-45/202 18% less -Mn myfile ## returns myfile byte 126/704 18% |
You can use less -N or –LINE-NUMBERS options which causes a line number to be displayed at the beginning of each line in the display.
1 2 3 4 5 6 |
## less -N or --LINE-NUMBERS options less myfile ## line number is not displayed by default less -N myfile ## line number is displayed at the begining ## of each new line |
You can use less -ofilename or –log-file=filename options which causes less to copy its input to the named file as it is being viewed. This applies only when the input file is a pipe, not an ordinary file. If the file already exists, less will ask for confirmation before overwriting. On the other hand less -Ofilename or –LOG-FILE=filename options is similar to -o option, but it will overwrite an existing file without asking for confirmation. If no log file has been specified, the -o and -O options can be used from within less to specify a log file. Without a file name, they will simply report the name of the log file. The “s” command is equivalent to specifying -o from within less.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## less -ofilename or -Ofilename options ps -aux | less ## only displays the output of ps -aux ps -aux | less -o mytmpfile ## saves the output to mytmpfile ls -l ps -aux | less -o mytmpfile ## gives a warning since mytmpfile already exist ## Warning: "mytmpfile" exists; ## Overwrite, Append or Don't log? A ps -aux | less -O mytmpfile ## no warning is given, overwrites mytmpfile rm mytmpfile |
You can use less -ppattern or –pattern=pattern options to start at the first occurrence of pattern in the file. This is equivalent to +/pattern command in the interactive mode.
1 2 3 |
## less -ppattern or --pattern=pattern options less -p "hello" myfile ## display start with hello |
You can use less -Pprompt or –prompt=prompt options to tailor the three prompt styles to your own preference. This option would normally be put in the LESS environment variable, rather than being typed in with each less command. Such an option must either be the last option in the LESS variable, or be terminated by a dollar sign.
1 2 3 4 5 6 |
## less -Pprompt or --prompt=prompt options less myfile ## displays default prompt (myfile) less -P="welcome" myfile ## in the interactive mode type = ## returns, welcome (press RETURN) |
You can use less -q or -Q options to execute less in quiet mode. less -q option causes moderately “quiet” operation: the terminal bell is not rung if an attempt is made to scroll past the end of the file or before the beginning of the file. If the terminal has a “visual bell”, it is used instead. The bell will be rung on certain other errors, such as typing an invalid character. The default is to ring the terminal bell in all such cases. The less -Q option causes totally “quiet” operation: the terminal bell is never rung. If the terminal has a “visual bell”, it is used in all cases where the terminal bell would have been rung.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## less -q or -Q options less myfile ## in the interactive mode, type a (rings bell) ## hit space bar to scroll to the end of file ## rings bell once end is reached less -q myfile ## in the interactive mode, type a (rings bell) ## hit space bar to scroll to the end of file ## does not rings bell once end is reached less -Q myfile ## in the interactive mode, type a (no bell) ## hit space bar to scroll to the end of file ## does not rings bell once end is reached |
You can use less -r or -R options to display control characters such as control-A. less -a option causes “raw” control characters to be displayed. The default is to display control characters using the caret notation; for example, a control-A (octal 001) is displayed as “^A”. less -R option is similar to -r, but only ANSI “color” escape sequences are output in “raw” form. Unlike -r, the screen appearance is maintained correctly in most cases. ANSI “color” escape sequences are sequences of the ESC [## where the “…” is zero or more color specification characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
## less -r or -R options ## create a long file with 256 lines with different colors > myfile for fgbg in 38 48 ; do # Foreground / Background for color in {0..255} ; do # Colors # Display the color printf "\e[${fgbg};5;%sm %3s \e[0m" $color $color >> myfile echo >> myfile done echo >> myfile done less myfile ## output not color-coded less -r myfile ## output is color-coded less -R myfile ## output is color-coded |
You can use less -s or –squeeze-blank-lines options which causes consecutive blank lines to be squeezed into a single blank line.
1 2 3 4 5 6 7 8 9 10 11 12 |
## less -s or --squeeze-blank-lines options ## create a file with multiple empty lines > myfile; i=1; while [ $i -le 20 ]; \ do echo "$i" >> myfile; ((i++)); done echo -e "\n\n\n\n\n\n\n\n" >> myfile i=21; while [ $i -le 200 ]; \ do echo "$i" >> myfile; ((i++)); done less myfile ## displays multiple empty line between 20 and 21 less -s myfile ## squeeze multiple blank lines into one |
You can use less -S or –chop-long-lines options which cause lines longer than the screen width to be chopped (truncated) rather than wrapped. That is, the portion of a long line that does not fit in the screen width is not shown. The default is to wrap long lines; that is, display the remainder on the next line.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## less -S or --chop-long-lines options ## create a file with long lines > myfile; i=1; while [ $i -le 20 ]; \ do echo "$i" >> myfile; ((i++)); done ps -ax | sed 's/[^A-Za-z0-9]//g' | tr -d '[ \n]' >> myfile echo >> myfile i=21; while [ $i -le 100 ]; \ do echo "$i" >> myfile; ((i++)); done less -N myfile ## warp long lines less -N -S myfile ## truncate long lines |
You can use less -u or –underline-special options which cause backspaces and carriage returns to be treated as printable characters. less -U or –UNDERLINE-SPECIAL option causes backspaces, tabs, carriage returns, and “formatting characters” (as defined by Unicode) to be treated as control characters. By default, if neither -u nor -U is given, backspaces which appear adjacent to an underscore character are treated specially.
1 2 3 4 5 6 7 |
## less -u or -U options echo -e "1\t2 2\b 3 4\c4" > myfile ## create a file with different special charecters less -u myfile ## returns 1 2 3 4 less -U myfile ## returns 1^I2 2^H 3 4 |
You can use less -w or –hilite-unread options which temporarily highlights the first “new” line after a forward movement of a full page. The first “new” line is the line immediately following the line previously at the bottom of the screen. It also highlights the target line after a g or p command. The highlight is removed at the next command which causes movement. The entire line is highlighted, unless the -J option is in effect, in which case only the status column is highlighted. less -W or –HILITE-UNREAD options is similar to -w, but temporarily highlights the first newline after any forward movement command larger than one line.
1 2 3 4 5 6 7 8 9 10 11 |
## less -w or -W options ## create a long file with 200 lines > myfile; i=1; while [ $i -le 200 ]; \ do echo "$i" >> myfile; ((i++)); done less myfile ## in interactive mode type z to forward 1 window ## no lines were highlighted in the next window less -w myfile ## in interactive mode type z to forward 1 window ## 1st line is highlighted in the next window |
You can use less -zn or –window=n or -n options which change the default scrolling window size to n lines. The default is one screenful. The z and w commands can also be used to change the window size. The “z” may be omitted for compatibility with some versions of more. If the number n is negative, it indicates n lines less than the current screen size. For example, if the screen is 24 lines, -z-4 sets the scrolling window to 20 lines. If the screen is resized to 40 lines, the scrolling window automatically changes to 36 lines.
1 2 3 4 5 6 7 8 |
## less -zn or --window=n or -n options tput lines ## returns current screen width less myfile ## in interactive mode type z to forward 1 window ## next window start from 46 less -z20 myfile ## in interactive mode type z to forward 1 window ## next window start from 20 |
You can use less -~ or –tilde options causes lines after end of file to be displayed as blank lines. Normally lines after end of file are displayed as a single tilde (~).
1 2 3 4 5 6 7 |
## less -~ or --tilde options less -c myfile ## in interactive mode type z to forward 1 window till eof ## lines after eof are displayed with ~ less -c --tilde myfile ## in interactive mode type z to forward 1 window till eof ## lines after eof are displayed with blank |
You can use less -# or –shift options to specify the default number of positions to scroll horizontally in the RIGHTARROW and LEFTARROW commands. If the number specified is zero, it sets the default number of positions to one half of the screen width. Alternately, the number may be specified as a fraction of the width of the screen, starting with a decimal point: .5 is half of the screen width, .3 is three tenths of the screen width, and so on.
1 2 3 4 5 6 7 8 9 10 11 |
## less -# or --shift options > myfile; i=1; while [ $i -le 200 ]; \ do echo -n "$i " >> myfile; ((i++)); done echo >> myfile tput cols ## check your current screen witdh less myfile ## in interactive mode, press right-arrow ## moves right to one-half of current screen width less --shift 20 myfile ## moves right to 20 characters |
Hope you have enjoyed this article. Less provides tons of options to format and interact with the less command. But due to time constraints, I and unable to give all the options example in this blog post. If you have other option examples, please write in the comment section and we will collate all and put in this blog. In the next blog post, we will discuss head command in Linux.