When you are parsing structured data in Linux, such as a CSV file or a system log, you rarely need to view the entire file. Usually, you only need to extract a specific piece of information, such as pulling just the usernames from the /etc/passwd file, or extracting the third column from a spreadsheet. The Linux cut command is designed specifically for this purpose, allowing you to slice sections out of lines of text based on byte position, character, or field delimiters.
Extracting Data by Fields (Columns)
The most common and powerful way to use cut is to extract specific fields (columns) from a file that uses a consistent delimiter (like a comma in a CSV file, or a colon in a system file). You use the -d flag to specify the delimiter, and the -f flag to specify which field number to extract.
For example, the standard Linux /etc/passwd file separates user data using a colon (:). The first column is always the username. To extract just the usernames, type:
cut -d ':' -f 1 /etc/passwd
If you wanted to extract both the username (field 1) and the user’s home directory (field 6), you would use a comma to select multiple fields:
cut -d ':' -f 1,6 /etc/passwd
Extracting Data by Character Position
If you are dealing with a file that has fixed-width formatting (where data always starts at a specific character count rather than being separated by commas), you can use the -c (character) flag.
If you have a log file where the first 10 characters of every line are a timestamp, and you only want to extract that timestamp, type:
cut -c 1-10 server_log.txt
This tells cut to grab characters 1 through 10 from every single line in the file and print them to the screen.
Using cut with Piped Output
You don’t need a physical file to use cut. It works perfectly with piped output from other commands. For example, if you run the ls -l command to list files in a directory, you might only want to extract the file permissions (which are the first 10 characters of the output).
ls -l | cut -c 1-10
This powerful combination allows you to instantly slice and dice the output of any command in the Linux terminal, stripping away the noise to leave only the exact data you require.