Chapter 22: Bash Remove Section (cut)

What does cut actually do? (super simple first)

cut = remove sections from each line of files (That’s literally what the man page says!)

It cuts out (extracts) only the parts you want from each line and prints them. You tell it:

  • Cut by characters (-c)
  • Cut by bytes (-b)
  • Cut by fields/columns (-f) using a delimiter (-d)

Think of it as a column selector or text slicer – very fast, very lightweight, perfect for logs, CSV, passwd file, who output, etc.

It does NOT edit the file – it shows the result on screen (or you redirect to new file).

1. Create test files right now (copy-paste these)

First – simple text file:

Bash

Second – comma separated (CSV-like):

Bash

Third – spaces/tabs example:

Bash

2. Three main ways to cut (these are the only modes!)

Mode Option When to use Example command
By character position -c Fixed-width text, no delimiters cut -c 1-5 file.txt
By byte position -b Same as -c in ASCII, different in UTF-8 cut -b 1-10 file.txt
By field/column -f + -d Delimited files (CSV, : , tab, space) cut -d ‘,’ -f 2 employees.csv

3. Most common usage – cut fields (columns) – 90% of real use

Default delimiter = TAB

But almost always we change it with -d

Bash

4. Change output delimiter (very useful!)

Bash

5. Cut by character position (-c)

Bash

Note: -c counts Unicode characters (good for emojis, non-ASCII)

6. Cut by bytes (-b) – rare unless dealing with binary-ish data

Bash

(Usually same as -c for English text)

7. Real-world examples you will use every day

Bash

8. Quick cheat-sheet table

Goal Command example Notes
First column (tab sep) cut -f 1 file.txt Default delimiter = tab
Second column (comma sep) cut -d ‘,’ -f 2 file.csv Most common
Columns 1 + 3 + 5 cut -d ‘,’ -f 1,3,5 file.csv List with commas
From column 2 to end cut -d ‘,’ -f 2- file.csv Drop first column
Characters 1 to 10 cut -c 1-10 file.txt Fixed width
Change output separator cut -d ‘,’ –output-delimiter=’;’ -f 1,2 file.csv Nice for new format
From pipe (no file) echo "a,b,c" cut -d ',' -f 2
Only first field + unique `cut -d ‘:’ -f 1 /etc/passwd sort

9. Pro tips from daily use

  • Always specify -d when not using tabs (most files are comma/space/colon)
  • Use –output-delimiter when you want pretty output
  • cut is very fast – great in pipelines (grep | cut | sort | uniq)
  • If fields have delimiter inside quotes → cut fails (use awk or csvkit instead)
  • Test on one line first: head -1 file.csv | cut -d ‘,’ -f 1-3

Now open your terminal and try these 3:

Bash

Tell me what you see! Or ask:

  • “How to cut only usernames from who command but skip empty lines?”
  • “How to cut IP addresses from ip addr output?”
  • “cut vs awk – when to use which?”

We’ll build exact commands together! 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *