首页·终端命令

cut

文本处理

用法

cut -d, -f2 [file]

切出固定字段或字符位置;分隔符只能是单个字符,且连续分隔符不会合并,所以按空格对齐的表格该交给 awk。

常用选项

选项含义
-dThe delimiter, exactly one character
-fWhich fields to keep, as in -f1,3 or -f2-
-cKeep character positions instead of fields
-bKeep byte positions
-sDrop lines that contain no delimiter at all
-wBSD and macOS: use runs of whitespace as the delimiter
--complementGNU: keep everything except the selection

示例

cut -d: -f1 /etc/passwd

Every user name.

cut -c1-8 access.log

The first eight characters of each line.

cut -d, -f2- data.csv

Everything from the second column on.

它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. cut 是做什么的?

切出固定字段或字符位置;分隔符只能是单个字符,且连续分隔符不会合并,所以按空格对齐的表格该交给 awk。

Q. 怎么写?

cut -d, -f2 [file] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 7 个,完整列表在 man cut。这条命令属于文本处理。

相关命令

man 手册: man cut