cut Commandcut命令

Remove sections from lines从行中删除部分内容

What is cut?什么是cut?

The cut command extracts specific columns or fields from each line of a file. It's incredibly useful for parsing CSV files, log files, or any delimited text data. You can cut by byte position, character position, or delimited fields.

cut命令从文件的每一行中提取特定的列或字段。对于解析CSV文件、日志文件或任何带分隔符的文本数据非常有用。你可以按字节位置、字符位置或分隔字段进行切割。

Basic Usage基本用法

$ cut -d: -f1 /etc/passwd
# Extract first colon-separated field
$ cut -c1-10 file.txt
# Extract characters 1-10 from each line
$ cut -d, -f2,4 data.csv
# Extract 2nd and 4th CSV columns
$ cut -d: -f1 /etc/passwd
# 提取第一个冒号分隔的字段
$ cut -c1-10 file.txt
# 从每行提取第1-10个字符
$ cut -d, -f2,4 data.csv
# 提取第2和第4个CSV列

Common Options常用选项

Option选项 Full Name完整名称 Description描述 Example示例
-d D delimiter分隔符 Use D as field delimiter使用D作为字段分隔符 cut -d: -f1 file.txt
-f N fields字段 Select Nth field(s)选择第N个字段 cut -f1,3 file.txt
-c N characters字符 Select Nth character(s)选择第N个字符 cut -c1-5 file.txt
-b N bytes字节 Select Nth byte(s)选择第N个字节 cut -b1-10 file.txt
-s only-delimited仅分隔 Skip lines without delimiter跳过没有分隔符的行 cut -s -d: -f1 file.txt
--complement complement补集 Select all except specified选择除指定外的所有 cut --complement -f1 file.txt

Practical Scenarios实际场景

Parse CSV Files解析CSV文件

$ cut -d, -f1,3,5 data.csv
# Extract columns 1, 3, and 5
$ cut -d, -f2- data.csv
# Extract from column 2 to end
$ cut -d, -f1,3,5 data.csv
# 提取第1、3和5列
$ cut -d, -f2- data.csv
# 提取从第2列到末尾

Extract Character Ranges提取字符范围

$ cut -c1-8 file.txt
# Extract first 8 characters
$ cut -c1-8 file.txt
# 提取前8个字符

Memory Tricks记忆技巧

✂️ "cut" = cut out columns - Like cutting with scissors!

✂️ "cut" = 剪切列 - 就像用剪刀剪一样!

🔪 -d = Delimiter - What separates your fields

🔪 -d = Delimiter(分隔符) - 分隔字段的内容

📋 -f = Fields - Which field(s) to extract

📋 -f = Fields(字段) - 要提取哪个字段

🔤 -c = Characters - Extract by character position

🔤 -c = Characters(字符) - 按字符位置提取

📏 N-M = Range - From N to M (e.g., 1-5, 3-, -5)

📏 N-M = Range(范围) - 从N到M(例如:1-5, 3-, -5)