less 命令详解与参数实测(Ubuntu 22.04)
less 分页器参数详解:行号、截断、颜色透传、follow 模式与无 tty 退化行为,Ubuntu 22.04 实测
less 命令详解与参数实测(Ubuntu 22.04)
目标:全面掌握 less 分页器的每一个常用参数——
-N行号、-S截断长行、-F一屏自动退出、-X退出不清屏、-RANSI 颜色透传、-i/-I搜索忽略大小写、-M详细提示、+F实时跟踪,并厘清无终端(无 tty)时 less 退化为直接输出的行为,全部命令与回显已在 Ubuntu 22.04(less 590)实测通过。
一、环境信息
本篇所有命令与回显均在以下环境实测采集,读者在同等版本环境可逐条复现。
- 操作系统:Ubuntu 22.04.5 LTS(x86_64)
- less 版本:less 590(GNU regular expressions,
less --version实测),Ubuntu 22.04 默认预装,无需额外安装 - 配套工具:GNU grep(配合
--color=always演示颜色透传)、util-linux 的script命令(用于在伪终端中驱动 less 交互)、cat -v(将控制字符可视化为^[形式) - 演示目录:
/root/demo/less/ - 测试数据:
sample.txt(5 行英文样例)、err.txt(3 行含 ERROR/error 大小写对照)、long.txt(40 行 record 样例)、wide.txt(单行 153 字符的超长行)、oneline.txt(1 行样例)
二、命令概览
less 是 Linux 下最常用的交互式分页器(pager),用于按屏查看大文件或管道输出,支持前后翻页、搜索、跳转,且打开大文件只需加载当前屏幕内容,速度远快于编辑器。man 手册的默认分页器就是 less。
💡 技术拓展:类 Unix 世界常见的分页器对比——
分页器 特点 适用场景 more 最早的分页器,只能向后翻页,功能最少 简单场景,兼容性要求极高 less 支持前后翻页、搜索、跳转,无需加载全文件 绝大多数交互查看场景,man 默认 most 支持多窗口、彩色高亮 需要多文件同屏对比 pg System V 风格分页器 老 Unix 系统维护 本文以 less 为例,它是 Ubuntu 22.04 的默认预装分页器,也是实际运维中最通用的选择。
2.1 语法与测试数据准备
less 的语法为 less 选项 文件(支持一次指定多个文件),最常用形态是 less 文件 交互查看、命令 | less 分页查看管道输出。less 的多数参数只在**交互终端(tty)**下才有意义;当标准输出不是终端(如管道、重定向)时,less 退化为直接输出。
先准备演示数据(覆盖普通文件、大小写对照、长文件、超长行):
mkdir -p /root/demo/less
cd /root/demo/less
printf 'first line\nsecond line\nthird line with ERROR\nfourth line\nfifth line with error\n' > sample.txt
printf 'first line\nsecond line with ERROR\nthird line with error\n' > err.txt
seq 1 40 | awk '{print "record-" $1}' > long.txt
head -c 150 /dev/zero | tr '\0' 'A' > /tmp/.w
printf '%sEND\n' "$(cat /tmp/.w)" > wide.txt
printf 'only one screen, auto quit\n' > oneline.txt
ls -l sample.txt err.txt long.txt wide.txt oneline.txt
数据就绪回显:
-rw-r--r-- 1 root root 56 Oct 15 07:42 err.txt
-rw-r--r-- 1 root root 391 Oct 15 07:42 long.txt
-rw-r--r-- 1 root root 27 Oct 15 07:42 oneline.txt
-rw-r--r-- 1 root root 79 Oct 15 07:42 sample.txt
-rw-r--r-- 1 root root 154 Oct 15 07:42 wide.txt
2.2 --help 全量回显
less --help 输出的是交互命令汇总 + 全部启动选项。由于交互命令部分较长,以下先摘录常用交互键所在的移动/搜索/跳转段(输出节选,实测首尾),随后完整保留全部选项行。
交互命令汇总段(输出节选,实测首尾):
SUMMARY OF LESS COMMANDS
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.
h H Display this help.
q :q Q :Q ZZ Exit.
---------------------------------------------------------------------------
MOVING
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 * Right one half screen width (or N positions).
ESC-( LeftArrow * Left one half screen width (or N positions).
ESC-} ^RightArrow Right to last column displayed.
ESC-{ ^LeftArrow Left to first column.
F Forward forever; like "tail -f".
ESC-F Like F but stop when search pattern is found.
r ^R ^L Repaint screen.
R Repaint screen, discarding buffered input.
---------------------------------------------------
Default "window" is the screen height.
Default "half-window" is half of the screen height.
---------------------------------------------------------------------------
SEARCHING
/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.
ESC-U Clear search highlighting.
&pattern * Display only matching lines.
---------------------------------------------------------------------------
JUMPING
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).
(以上为交互命令汇总节选;--help 还包含 CHANGING FILES、MISCELLANEOUS COMMANDS 段与 LINE EDITING 段,此处从略,可自行执行 less --help 查看。)
全部启动选项行(实测完整保留):
-? ........ --help
Display help (from command line).
-a ........ --search-skip-screen
Search skips current screen.
-A ........ --SEARCH-SKIP-SCREEN
Search starts just after target line.
-b [N] .... --buffers=[N]
Number of buffers.
-B ........ --auto-buffers
Don't automatically allocate buffers for pipes.
-c ........ --clear-screen
Repaint by clearing rather than scrolling.
-d ........ --dumb
Dumb terminal.
-D xcolor . --color=xcolor
Set screen colors.
-e -E .... --quit-at-eof --QUIT-AT-EOF
Quit at end of file.
-f ........ --force
Force open non-regular files.
-F ........ --quit-if-one-screen
Quit if entire file fits on first screen.
-g ........ --hilite-search
Highlight only last match for searches.
-G ........ --HILITE-SEARCH
Don't highlight any matches for searches.
-h [N] .... --max-back-scroll=[N]
Backward scroll limit.
-i ........ --ignore-case
Ignore case in searches that do not contain uppercase.
-I ........ --IGNORE-CASE
Ignore case in all searches.
-j [N] .... --jump-target=[N]
Screen position of target lines.
-J ........ --status-column
Display a status column at left edge of screen.
-k [file] . --lesskey-file=[file]
Use a lesskey file.
-K ........ --quit-on-intr
Exit less in response to ctrl-C.
-L ........ --no-lessopen
Ignore the LESSOPEN environment variable.
-m -M .... --long-prompt --LONG-PROMPT
Set prompt style.
-n -N .... --line-numbers --LINE-NUMBERS
Don't use line numbers.
-o [file] . --log-file=[file]
Copy to log file (standard input only).
-O [file] . --LOG-FILE=[file]
Copy to log file (unconditionally overwrite).
-p [pattern] --pattern=[pattern]
Start at pattern (from command line).
-P [prompt] --prompt=[prompt]
Define new prompt.
-q -Q .... --quiet --QUIET --silent --SILENT
Quiet the terminal bell.
-r -R .... --raw-control-chars --RAW-CONTROL-CHARS
Output "raw" control characters.
-s ........ --squeeze-blank-lines
Squeeze multiple blank lines.
-S ........ --chop-long-lines
Chop (truncate) long lines rather than wrapping.
-t [tag] .. --tag=[tag]
Find a tag.
-T [tagsfile] --tag-file=[tagsfile]
Use an alternate tags file.
-u -U .... --underline-special --UNDERLINE-SPECIAL
Change handling of backspaces.
-V ........ --version
Display the version number of "less".
-w ........ --hilite-unread
Highlight first new line after forward-screen.
-W ........ --HILITE-UNREAD
Highlight first new line after any forward movement.
-x [N[,...]] --tabs=[N[,...]]
Set tab stops.
-X ........ --no-init
Don't use termcap init/deinit strings.
-y [N] .... --max-forw-scroll=[N]
Forward scroll limit.
-z [N] .... --window=[N]
Set size of window.
-" [c[c]] . --quotes=[c[c]]
Set shell quote characters.
-~ ........ --tilde
Don't display tildes after end of file.
-# [N] .... --shift=[N]
Set horizontal scroll amount (0 = one half screen width).
--file-size
Automatically determine the size of the input file.
--follow-name
The F command changes files if the input file is renamed.
--incsearch
Search file as each pattern character is typed in.
--line-num-width=N
Set the width of the -N line number field to N characters.
--mouse
Enable mouse input.
--no-keypad
Don't send termcap keypad init/deinit strings.
--no-histdups
Remove duplicates from command history.
--rscroll=C
Set the character used to mark truncated lines.
--save-marks
Retain marks across invocations of less.
--status-col-width=N
Set the width of the -J status column to N characters.
--use-backslash
Subsequent options use backslash as escape char.
--use-color
Enables colored text.
--wheel-lines=N
Each click of the mouse wheel moves N lines.
常用交互键速查(依据上面 --help 回显原文整理成表):
| 按键 | --help 原文 | 作用 |
|---|---|---|
| 空格 / f | f ^F ^V SPACE * Forward one window | 向后翻一屏 |
| b | b ^B ESC-v * Backward one window | 向前回一屏 |
| /pattern | /pattern * Search forward for (N-th) matching line. | 向下搜索 |
| n | n * Repeat previous search (for N-th occurrence). | 跳到下一处匹配 |
| g | g < ESC-< * Go to first line in file | 跳到文件首行 |
| G | G > ESC-> * Go to last line in file | 跳到文件末行 |
| F | F Forward forever; like "tail -f". | 进入实时跟踪(等价 +F 启动参数) |
| q | q :q Q :Q ZZ Exit. | 退出 less |
2.3 版本确认
确认当前 less 版本(文档后续回显均基于此版本):
$ less --version
less 590 (GNU regular expressions)
Copyright (C) 1984-2021 Mark Nudelman
less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Home page: https://greenwoodsoftware.com/less
三、参数逐项实测
本章逐个参数实测。因为 less 的核心能力是交互式查看,凡涉及屏幕显示效果的参数,均用 script -qec '...' /tmp/.tsN 在**伪终端(pty)**中驱动 less 交互(按键 q 退出),再用 cat -v 把终端控制字符可视化为 ^[[、^M 形式记录——所有回显都是真实终端会话的逐字节记录,其中 ^[[7m...^[[27m 是反显(高亮)样式、^M 是回车符、开头的孤立 q 是退出按键的时序痕迹。
3.1 无 tty 时退化为直接输出
先看一个关键前提:当标准输出不是终端(管道、重定向、脚本采集)时,less 不进入交互模式,直接把输入原样写到 stdout,所有交互参数(行号、截断、提示条)均不生效:
$ less sample.txt
first line
second line
third line with ERROR
fourth line
fifth line with error
$ cat oneline.txt | less
only one screen, auto quit
$ less -F oneline.txt
only one screen, auto quit
三条命令的输出与 cat 无异。这正是脚本/管道中「less 不会卡住等待交互」的原因。
💡 说明:这意味着本文后续的伪终端实测才是参数的真实效果;无 tty 场景下这些参数等于不存在。管道中想保留行号/截断效果,应改用
nl、cut等工具。
3.2 -N(--line-numbers):每行开头显示行号
在伪终端中查看 sample.txt:
$ grep -v "^Script " /tmp/.ts1 | cat -v
q^[[?1049h^[[22;0;0t^[[?1h^[=^M 1 first line^M
2 second line^M
3 third line with ERROR^M
4 fourth line^M
5 fifth line with error^M
^[[7msample.txt (END)^[[27m^[[K^M^[[K^[[?1l^[>^[[?1049l^[[23;0;0t
去除控制序列后,屏幕实际呈现为:
1 first line
2 second line
3 third line with ERROR
4 fourth line
5 fifth line with error
sample.txt (END)
要点:行号占 6 列右对齐;底部状态行显示当前文件与位置((END) 表示已到末尾)。
3.3 -S(--chop-long-lines):截断超长行而不是折行
wide.txt 是一行 153 字符的超长行。终端宽度压到 40 列实测:
$ grep -v "^Script " /tmp/.ts2 | cat -v
q^[[?1049h^[[22;0;0t^[[?1h^[=^MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA^[[7m>^[[27m^M
^[[7mwide.txt (END)^[[27m^[[K^M^[[K^[[?1l^[>^[[?1049l^[[23;0;0t
去除控制序列后屏幕为:39 个 A 后跟一个反显 > 标记,说明本行右侧还有内容被截断;不带 -S 时该行会折成 4 行逐屏显示。截断后可用方向键(ESC-) 右移半屏)横向查看被截断部分。
对照:同一文件在无 tty 的管道里,-S 不生效(输出完整行),下面用 cut 截取前 45 字符验证行仍是完整的:
$ less -S wide.txt | cut -c1-45
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
3.4 -F(--quit-if-one-screen):内容一屏放得下时自动退出
文件小于一屏时,less 显示后自动退出、不进入交互,适合在脚本里「能一屏看完就看完」:
$ grep -v "^Script " /tmp/.ts3 | cat -v
q^Monly one screen, auto quit^M
^M^[[K
屏幕上只留下这行内容,没有状态行、没有等待按键。与 3.2 的回显对比可见 -F 连反显状态行都没有——它根本没进入交互界面。
3.5 -X(--no-init):退出时不清理终端屏幕
默认情况下 less 启动时发送终端初始化序列(进入备用屏幕),退出时发送清理序列恢复原屏,查看内容不会留在屏幕上。-X 禁用这两个序列,退出后内容保留在主屏幕:
$ grep -v "^Script " /tmp/.ts4 | cat -v
q^[[?1h^[=^M 1 first line^M
2 second line^M
3 third line with ERROR^M
4 fourth line^M
5 fifth line with error^M
^[[7msample.txt (END)^[[27m^[[K^M^[[K^[[?1l^[>
对比 3.2 的结尾:无 -X 时以 ^[[?1049l^[[23;0;0t 结束(退出备用屏幕、恢复主屏),有 -X 时结尾止于 ^[[?1l^[>(未发送退出备用屏幕的序列),内容因此留在屏幕上。日志文件查看(less 日志文件 退出后还想滚动回看)时 -X 很实用。
3.6 -R(--RAW-CONTROL-CHARS):ANSI 颜色转义序列透传
管道中查看 grep --color=always 等彩色输出时,默认 less 会把 ANSI 转义序列显示为反显的 ESC 字样;-R 让 less 解释并透传颜色。先看 -R 的效果(日志中 ^[[01;31m 是红色加粗的颜色码,终端上 ERROR 显示为红色):
$ grep -v "^Script " /tmp/.ts5 | cat -v | head -4
q^[[?1049h^[[22;0;0t^[[?1h^[=^Msecond line with ^[[01;31mERROR^[[m^[[m^M
^[[7m(END)^[[27m^[[K^M^[[K^[[?1l^[>^[[?1049l^[[23;0;0t
再看不加 -R 的默认行为——转义序列没有被执行,而是以反显 ESC 字样直接显示出来:
$ grep -v "^Script " /tmp/.ts6 | cat -v | head -4
q^[[?1049h^[[22;0;0t^[[?1h^[=^Msecond line with ^[[7mESC^[[27m[01;31m^[[7mESC^[[27m[KERROR^[[7mESC^[[27m[m^[[7mESC^[[27m[K^M
^[[7m(END)^[[27m^[[K^M^[[K^[[?1l^[>^[[?1049l^[[23;0;0t
💡 说明:
grep --color=always强制输出颜色码(默认检测到管道会关闭颜色);查看管道彩色输出时记组合命令 --color=always | less -R。姊妹参数-r更激进(原样透传全部控制字符,可能打乱排版),日常用-R即可。
3.7 -M(--LONG-PROMPT):详细提示信息
默认提示只显示 (END) 或文件名加百分比;-M 在状态行追加行号区间与字节偏移。用 40 行的 long.txt 实测(-F 保证一屏放得下时自动退出,此处文件 40 行超出一屏会进入交互,按 q 退出):
$ grep -v "^Script " /tmp/.ts7 | cat -v | tail -3
record-8^M
record-9^M
^[[7mlong.txt lines 1-9/40 21%^[[27m^[[K^M^[[K^[[?1l^[>^[[?1049l^[[23;0;0t
反显状态行内容为 long.txt lines 1-9/40 21%:当前显示第 1–9 行、共 40 行、进度 21%。短提示(-m)则只显示 long.txt 21%。
3.8 +F 启动参数:进入 follow 模式实时跟踪
+命令 是 less 的通用启动形态(在文件打开后先执行指定的交互命令)。+F 等价于打开文件后按 F 键,进入类似 tail -f 的实时跟踪模式,新写入内容会持续滚动显示,底部提示等待状态;按 Ctrl-C 中断跟踪回到交互、按 q 退出 less。实测(打开 2 秒后发送 q):
$ grep -v "^Script " /tmp/.ts8 | cat -v | tail -4
record-38^M
record-39^M
record-40^M
^M^[[K^[[7mWaiting for data... (interrupt to abort)^[[27m
反显的 Waiting for data... (interrupt to abort) 正是 follow 模式的标志——less 已读完文件全部 40 行并持续等待新数据。
💡 说明:查看持续写入的日志时,
less +F /var/log/syslog比tail -f的优势是可以随时Ctrl-C暂停跟踪、用/搜索历史内容,再按F恢复跟踪。
3.9 -i(--ignore-case)与 -I(--IGNORE-CASE):搜索忽略大小写
两者都是搜索参数,差异在大小写敏感度:-i 只在搜索词全小写时忽略大小写(含大写则精确匹配);-I 无条件忽略大小写。先看 --help 中的原文定义:
$ less --help | grep -A2 "^ -i "
-i ........ --ignore-case
Ignore case in searches that do not contain uppercase.
-I ........ --IGNORE-CASE
$ less --help | grep -A2 "^ -I "
-I ........ --IGNORE-CASE
Ignore case in all searches.
-j [N] .... --jump-target=[N]
再在伪终端中实测 -i 下搜索小写 error(err.txt 中同时存在大写 ERROR 与小写 error):输入 /error 回车后 less 定位并高亮匹配,输入 n 跳到下一处,两次命中分别落在 second line with ERROR 与 third line with error,说明大写行也被搜到了:
$ grep -v "^Script " /tmp/.ts9 | cat -v | head -5
^[[?1049h^[[22;0;0t^[[?1h^[=^Mfirst line^M
second line with ERROR^M
third line with error^M
^[[7merr.txt (END)^[[27m^[[K^M^[[K/^[[Ke^He^[[Kr^Hr^[[Kr^Hr^[[Ko^Ho^[[Kr^Hr^M^[[K...skipping...^M
first line^M
💡 说明:日志片段中
/error逐字符回显、...skipping...是 less 搜索后重新定位屏幕的痕迹;交互中的高亮在cat -v记录里体现为反显序列。日常用-I语义最直观;-i适合「输大写就精确、输小写就宽松」的场景。
3.10 组合使用:-F -X 与管道彩色输出
-F -X 组合适用于脚本一次性展示短文本(显示完自动退出且不清屏):
$ less -F -X oneline.txt
only one screen, auto quit
-R -N 组合在管道彩色输出中同时透传颜色与加行号(无 tty 下 less 直接输出,颜色码原样保留,此处用 cat -v 可视化确认颜色码存在):
$ grep --color=always ERROR sample.txt | less -R -N | cat -v
third line with ^[[01;31m^[[KERROR^[[m^[[K
四、实战示例
以下示例均在本环境实测执行。
4.1 分页查看大日志并实时跟踪
对持续写入的日志文件(如 /var/log/syslog),用启动参数 +F 直接进入实时跟踪模式:
less +F /var/log/syslog
打开后立即进入跟踪状态,屏幕底部出现 Waiting for data... (interrupt to abort) 提示(该提示已在 3.8 节伪终端实测);按 Ctrl-C 暂停跟踪后可用 /error 向下搜索、n 跳下一处、G 跳到最新末尾、再按 F 恢复跟踪、q 退出。
4.2 管道分页查看彩色 grep 结果
$ grep --color=always -n ERROR sample.txt | less -R | cat -v
^[[32m^[[K3^[[m^[[K^[[36m^[[K:^[[m^[[Kthird line with ^[[01;31m^[[KERROR^[[m^[[K
-R 保证行号(青色)、冒号与命中词(红色加粗)的颜色码全部透传;在 less 内按 &ERROR 可只显示命中行(& 是 less 的过滤命令,见 2.2 节 SEARCHING 段原文)。
4.3 脚本中安全展示短输出
$ free -h | less -FX
total used free shared buff/cache available
Mem: 39Gi 18Gi 672Mi 58Mi 20Gi 20Gi
Swap: 2.0Gi 2.0Mi 2.0Gi
-F 一屏放得下自动退出(脚本不会卡住等待按键),-X 退出后内容留在屏幕上供继续查看。注意无 tty 时(如本条在采集脚本中执行)内容是直接输出的,效果等同于管道直通。
4.4 一次性携带显示偏好
less -NMS long.txt
一次性携带行号(-N)、详细提示(-M)、截断长行(-S)三个显示偏好;在交互终端中打开即生效。也可以把常用偏好写入环境变量 export LESS='-NMSR' 永久生效(对 man 手册同样有效,man 默认用 less 分页)。
五、注意事项与常见问题
Q1:为什么在脚本或管道里执行 less,输出和 cat 一样,什么参数都没效果?
当 stdout 不是终端时,less 自动退化为直接输出(见 3.1 实测)。这是设计行为:防止脚本因等待交互而卡死。要验证参数效果需在真实终端运行,或用 script -qec 'less 目标文件' /dev/null 这类伪终端方式驱动。
Q2:man less 打开的手册颜色丢失、退出后屏幕内容消失?
man 的分页器就是 less。颜色丢失多为没有 -R;退出后内容消失是终端备用屏幕机制(默认行为),加上 -X(或 export LESS='-X')退出后内容就留在屏幕上。
Q3:less -N 的行号为什么从 1 开始但占位很宽、能否变窄?
默认行号字段固定 6 列右对齐;less 590 支持 --line-num-width=N 自定义宽度(见 2.2 节选项行原文)。
Q4:+F 与 tail -f 有什么区别?
+F 本质是 less 的 F 交互命令,随时可暂停(Ctrl-C)后搜索、跳转,再按 F 恢复;tail -f 是持续输出进程,只能中断重开。对大日志的「边看边搜」场景 less +F 更灵活。
Q5:搜索后屏幕上残留的高亮如何清除?
按 ESC-u 取消(切换)高亮、ESC-U 彻底清除高亮(见 2.2 节 SEARCHING 段原文)。
六、参考链接
- less 官方主页(版本与源码):https://greenwoodsoftware.com/less/
- less 590 手册页:
man less(终端内执行) - GNU grep 颜色输出选项:
man grep(--color=always 说明) - util-linux script 命令(伪终端录制):
man script