cut 命令行使用教程
cut
是一个用于提取文本中特定字段或字符的命令。它可以按列(字段)或字符位置提取数据,常用于处理以特定分隔符分隔的文本。
Usage: cut OPTION... [FILE]...
Print selected parts of lines from each FILE to standard output.
With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-b, --bytes=LIST select only these bytes
-c, --characters=LIST select only these characters
-d, --delimiter=DELIM use DELIM instead of TAB for field delimiter
-f, --fields=LIST select only these fields; also print any line
that contains no delimiter character, unless
the -s option is specified
-n (ignored)
--complement complement the set of selected bytes, characters
or fields
-s, --only-delimited do not print lines not containing delimiters
--output-delimiter=STRING use STRING as the output delimiter
the default is to use the input delimiter
-z, --zero-terminated line delimiter is NUL, not newline
--help display this help and exit
--version output version information and exit
Use one, and only one of -b, -c or -f. Each LIST is made up of one
range, or many ranges separated by commas. Selected input is written
in the same order that it is read, and is written exactly once.
Each range is one of:
N N'th byte, character or field, counted from 1
N- from N'th byte, character or field, to end of line
N-M from N'th to M'th (included) byte, character or field
-M from first to M'th (included) byte, character or field
1. 主要参数
(1)按字段提取(-f + -d)
语法
cut -d'分隔符' -f字段号 文件名
参数说明
-d '分隔符'
:指定字段分隔符(默认为 TAB)。
-f 字段号
:选择要提取的字段(字段号从 1 开始)。
- 多个字段可以用逗号
,
或者 -
表示范围。
示例
echo "apple,banana,orange" | cut -d',' -f2
输出:
banana
echo "apple,banana,orange" | cut -d',' -f1,3
输出:
apple,orange
echo "apple,banana,orange" | cut -d',' -f2-
输出(从第 2 个字段开始):
banana,orange
(2)按字符位置提取(-c)
语法
cut -c字符位置 文件名
参数说明
-c 字符号
:按字符索引提取(索引从 1 开始)。
- 可以指定单个字符,也可以用逗号
,
分隔多个字符,或者 -
指定范围。
示例
echo "HelloWorld" | cut -c1-5
输出:
Hello
echo "HelloWorld" | cut -c2,4,6
输出:
elW
(3)按字节提取(-b)
语法
cut -b字节位置 文件名
参数说明
-b 字节号
:按照字节索引提取(适用于 ASCII)。
- ⚠️注意:对于 UTF-8 编码的多字节字符,
-b
可能会截断字符,推荐使用 -c
。
示例
echo "Hello" | cut -b1-2
输出:
He
2. 组合参数
cut
只能 按字段(-f)、字符(-c) 或 字节(-b) 之一操作,不能混用。
例如:
echo "user:pass:email" | cut -d':' -f2
输出:
pass
echo "HelloWorld" | cut -c1-5
输出:
Hello
3. 实际应用
(1)获取 /etc/passwd
文件的用户名
cut -d':' -f1 /etc/passwd
输出(示例):
root
daemon
bin
sys
(2)获取文件的扩展名
echo "file.tar.gz" | cut -d'.' -f2-
输出:
tar.gz
4. cut
VS awk
VS rev
命令 | 适用场景 | 主要功能 |
cut | 简单字段提取 | 适用于固定格式的文本,如 CSV 或 /etc/passwd |
awk | 高级文本处理 | 支持更复杂的逻辑、条件判断 |
rev | 反转字符串 | 适用于需要从末尾提取数据的情况 |
总结
cut -d'分隔符' -fN
→ 按分隔符提取字段(适用于 CSV、日志等)
cut -cN-M
→ 按字符位置提取(适用于固定格式文本)
cut -bN-M
→ 按字节提取(不推荐用于 UTF-8)
cut
适合简单的文本处理,复杂操作可用 awk
或 sed