Enhancing Skills

cut: Extract sections from each line of input

The cut command is used to extract sections from each line of input files or streams. It operates on text files or input streams and allows you to select specific columns or fields based on delimiters.

Basic Syntax

cut [options] [file...]

Options

  • -f : Specifies which fields to extract.
  • -d : Sets the delimiter to use for field separation (default is TAB).
  • -c : Specifies character positions to extract.

Examples


1. Extract Specific Fields from a CSV File

Command:

cut -d ',' -f 1,3 data.csv

Sample File (data.csv):

Name,Age,Occupation
Alice,30,Engineer
Bob,25,Designer
Charlie,35,Manager

Sample Output:

Name,Occupation
Alice,Engineer
Bob,Designer
Charlie,Manager

Explanation:

  • -d ',': Sets the delimiter to a comma.
  • -f 1,3: Extracts the 1st and 3rd fields.

2. Extract Specific Character Positions

Command:

cut -c 1-5 file.txt

Sample File (file.txt):

1234567890
abcdefghij
ABCDE12345

Sample Output:

12345
abcde
ABCDE

Explanation:

  • -c 1-5: Extracts characters from positions 1 to 5.

3. Extract Fields from a TAB-Separated File

Command:

cut -f 2 -d $'\t' file.tsv

Sample File (file.tsv):

Name\tAge\tOccupation
Alice\t30\tEngineer
Bob\t25\tDesigner
Charlie\t35\tManager

Sample Output:

Age
30
25
35

Explanation:

  • -d $'\t': Sets the delimiter to a TAB character.
  • -f 2: Extracts the 2nd field.

Summary

The cut command is useful for quickly extracting specific fields or characters from text files or streams. It’s particularly handy for processing delimited files like CSV or TSV, as well as for selecting portions of text based on character positions.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.