When analyzing large logs or processing data in the Linux terminal, you frequently encounter text files containing thousands of lines structured into columns, such as CSV (Comma-Separated Values) files or system logs. If you only need to extract the email addresses from the third column of a massive user database, opening the file in a text editor and deleting the other columns manually is impossible. Instead, you can use the Linux cut command to surgically extract only the specific vertical slices of data you need.
How the cut Command Works
The cut command works by analyzing a text file, identifying the “delimiter” (the character that separates the columns, such as a comma, a colon, or a space), and then printing only the specific field (column number) you request.
The basic syntax is: cut -d"delimiter" -f[field_number] filename.txt
Extracting a Single Column
Suppose you have a file named users.csv formatted like this:
John,Smith,[email protected],555-1234Jane,Doe,[email protected],555-5678
Because this is a CSV file, the data columns are separated by commas. To extract only the email addresses (which reside in the 3rd column), open your terminal and type:
cut -d"," -f3 users.csv
Press Enter. The -d"," flag tells the command that the columns are separated by commas, and the -f3 flag tells it to only print the 3rd column. The terminal will instantly output:
[email protected][email protected]
Extracting Multiple Columns
If you need more than one column, you can specify multiple fields separated by commas. For example, to extract both the first names (column 1) and the phone numbers (column 4):
cut -d"," -f1,4 users.csv
The output will be:
John,555-1234Jane,555-5678
Working with System Files (Colon Delimiters)
Many critical Linux system files use colons instead of commas to separate data. For instance, the /etc/passwd file contains user account information, where the first column is the username.
To print a clean list of every username registered on the system, you must tell the cut command to look for colons instead:
cut -d":" -f1 /etc/passwd
This will output a simple, single-column vertical list of usernames, ignoring all the complex directory paths and shell configurations stored in the other columns of the file.