The Wayback Machine - https://web.archive.org/web/20240823063824/https://www.geeksforgeeks.org/cut-command-linux-examples/
Open In App

cut command in Linux with examples

Last Updated : 12 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The cut command in linux is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character, and field. The cut command slices a line and extracts the text. It is necessary to specify an option with a command otherwise it gives an error. If more than one file name is provided then data from each file is not preceded by its file name.

Syntax of cut Command

The basic syntax of the cut command is:

cut OPTION... [FILE]...

Where

`OPTION` specifies the desired behavior

`FILE` represents the input file.

Note: If FILE is not specified, `cut` reads from standard input (stdin).

Options Available in cut Command

Here is a list of the most commonly used options with the `cut` command:

Option

Description

-b, –bytes=LIST

Selects only the bytes specified in LIST (e.g., -b 1-3,7).

-c, –characters=LIST

Selects only the characters specified in LIST (e.g., -c 1-3,7).

-d, –delimiter=DELIM

Uses DELIM as the field delimiter character instead of the tab character.

-f, –fields=LIS

Selects only the fields specified in LIST, separated by the delimiter character (default is tab).

-n

Do not split multi-byte characters (no effect unless -b or -c is specified).

–complement

Invert the selection of fields/characters. Print the fields/characters not selected.

Practical Examples of cut Command

Let us consider two files having name state.txt and capital.txt contains 5 names of the Indian states and capitals respectively.

$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

Without any option specified it displays error.

$ cut state.txt
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.



Extract Specific Bytes (-b) Using cut Command

-b(byte): To extract the specific bytes, you need to follow -b option with the list of byte numbers separated by comma. Range of bytes can also be specified using the hyphen(-). It is necessary to specify list of byte numbers otherwise it gives error.

Tabs and backspaces are treated like as a character of 1 byte.

List without ranges:

cut -b 1,2,3 state.txt

list without range

list without range

List with ranges:

cut -b 1-3,5-7 state.txt

list with range

list with range

It uses a special form for selecting bytes from beginning upto the end of the line:

Special Form: Selecting bytes from beginning to end of line

In this, 1- indicate from 1st byte to end byte of a line

cut -b 1- state.txt

special form

special form with -b option

In this, -3 indicate from 1st byte to 3rd byte of a line

cut -b -3 state.txt

special form

special form -b option

Cut by Character (-c) Using cut Command

-c (column): To cut by character use the -c option. This selects the characters given to the -c option. This can be a list of numbers separated comma or a range of numbers separated by hyphen(-).

Tabs and backspaces are treated as a character. It is necessary to specify list of character numbers otherwise it gives error with this option.

Syntax:

cut -c [(k)-(n)/(k),(n)/(n)] filename

Here,k denotes the starting position of the character and n denotes the ending position of the character in each line, if k and n are separated by “-” otherwise they are only the position of character in each line from the file taken as an input.

Extract specific characters:

cut -c 2,5,7 state.txt

Extract specific characters

Extract specific characters

Above cut command prints second, fifth and seventh character from each line of the file.

Extract first seven characters:

cut -c 1-7 state.txt

Extract first seven characters

Extract first seven characters

Above cut command prints first seven characters of each line from the file. Cut uses a special form for selecting characters from beginning upto the end of the line:

Special Form: Selecting characters from beginning to end of line

cut -c 1- state.txt

selecting characters from beginning to end of line

selecting characters from beginning to end of line using -c option

Above command prints starting from first character to end. Here in command only starting position is specified and the ending position is omitted.

cut -c -5 state.txt

selecting characters from beginning to end of line using -c option

selecting characters from beginning to end of line using -c option

Above command prints starting position to the fifth character. Here the starting position is omitted and the ending position is specified.

Cut by Field (-f) Using cut Command

-f (field): -c option is useful for fixed-length lines. Most unix files doesn’t have fixed-length lines. To extract the useful information you need to cut by fields rather than columns. List of the fields number specified must be separated by comma. Ranges are not described with -f option. cut uses tab as a default field delimiter but can also work with other delimiter by using -d option.

Note: Space is not considered as delimiter in UNIX.

Syntax:

cut -d "delimiter" -f (field number) file.txt

Extract first field :

Like in the file state.txt fields are separated by space if -d option is not used then it prints whole line:

cut -f 1 state.txt

Extract first field using -f option

Extract first field using -f option

If `-d` option is used then it considered space as a field separator or delimiter:

cut -d " " -f 1 state.txt

space as a field separator or delimiter

space as a field separator or delimiter

Extract fields 1 to 4:

Command prints field from first to fourth of each line from the file.

cut -d " " -f 1-4 state.txt

Command prints field from first to fourth

Command prints field from first to fourth

Complement Output (--complement) Using cut Command

–complement: As the name suggests it complement the output. This option can be used in the combination with other options either with -f or with -c.

cut --complement -d " " -f 1 state.txt

--complement

–complement

cut --complement -c 5 state.txt

--complement

–complement

Output Delimiter (--output-delimiter) Using cut Command

–output-delimiter: By default the output delimiter is same as input delimiter that we specify in the cut with -d option. To change the output delimiter use the option –output-delimiter=”delimiter”.

cut -d " " -f 1,2 state.txt --output-delimiter='%'

2024-02-16_13-18

Here cut command changes delimiter(%) in the standard output between the fields which is specified by using -f option .

Display Version (--version) Using cut Command

–version: This option is used to display the version of cut which is currently running on your system.

cut --version

display version of cut command

display version of cut command

How to use tail with pipes(|) in cut Command

The cut command can be piped with many other commands of the unix. In the following example output of the cat command is given as input to the cut command with -f option to sort the state names coming from file state.txt in the reverse order.

cat state.txt | cut -d ' ' -f 1 | sort -r

using tail with pipe (|) in cut command

using tail with pipe (|) in cut command

It can also be piped with one or more filters for additional processing. Like in the following example, we are using cat, head and cut command and whose output is stored in the file name list.txt using directive(>).

cat state.txt | head -n 3 | cut -d ' ' -f 1 > list.txt
cat list.txt

redirecting output in different file

redirecting output in different file

Frequently Asked Questions on cut Command in Linux – FAQs

How do I use the cut command to extract specific columns from a file?

Example: To extract the first and third columns from a CSV file named `data.csv`.

cut -d',' -f1,3 data.csv

Can I use cut to extract a range of characters from each line?

Yes, you can. To extract characters 5 to 10 from each line of a file named text.txt.

cut -c5-10 text.txt

How can I change the delimiter used by the cut command?

Use the `-d` option followed by the delimiter character. For example, to use a colon (:) as the delimiter.

cut -d':' -f1,3 data.txt

Is it possible to use cut to extract fields based on character position?

Yes, you can specify character positions with the `-c` option. For example, to extract characters 1 to 5 and 10 to 15 from each line.

cut -c1-5,10-15 data.txt

How do I use cut to extract fields based on a specific delimiter and store them in a new file?

To extract fields separated by commas and store them in a new file named `output.txt`

cut -d',' -f1,3 data.csv > output.txt

Conclusion

In this article we discussed the `cut` command in Linux which is a versatile tool for extracting specific sections from files based on byte position, character, or field. It slices lines of text and outputs the extracted data. Failure to specify an option with the cut command results in an error. Multiple files can be processed, but the output does not include the file names. Options such as `-b`, `-c`, and `-f` allow extraction by byte, character, and field, respectively. The --complement option inverts the selection, printing what is not selected, and --output-delimiter changes the output delimiter. The command also includes options for version display and can be used in combination with other commands through pipes for additional processing.

cut command in Linux with examples – FAQs

What is cut in Linux command?

The cut command is used to extract sections from each line of input data. It can extract based on character, byte, or field (column) positions. This command is commonly used in text processing and data manipulation tasks.

How to Cut a File in Linux Terminal?

To “cut” in the context of the cut command means to extract specific parts of a file. Here are some examples of how to use the cut command:

Extracting Columns by Delimiter

Assuming you have a file called data.txt with the following content:

name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago

To extract the first column (names):

cut -d',' -f1 data.txt

Output:

name
Alice
Bob
Charlie

Extracting Specific Characters

If you want to extract the first five characters of each line:

cut -c1-5 data.txt

Output:

name,
Alice
Bob,2
Charl

How to Cut a Word in Linux?

To cut a word from each line in a file, use the cut or awk command:

  • Using cut: Extract the second word.
  • Using awk: Extract the second word.
cut -d' ' -f2 filename.txt
awk '{print $2}' filename.txt

What is split Command in Linux?

The split command splits a file into smaller files.

  • By lines:
  • By size:
split -l 10 largefile.txt
split -b 1M largefile.txt

How Do I Delete One Word in Linux?

To delete a specific word from a file, use sed or awk:

  • Using sed: Remove the word “word”.
  • Using awk: Remove the second word.
sed 's/word//g' filename.txt
awk '{$2=""; print $0}' filename.txt

    https://www.youtube.com/playlist?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L



    Previous Article
    Next Article

    Similar Reads

    Ccat – Colorize Cat Command Output command in Linux with Examples
    ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages. JavaScriptJavaRubyPythonGoCJSONInstallation of Ccat First, we are going to see
    2 min read
    How to Display Command History in Linux | history Command
    The command-line interface in Linux provides powerful tools for users, and mastering command history is essential for efficient navigation and retrieval of previously executed commands. The history command is a valuable utility that allows users to view and search through their command history. In this comprehensive guide, we will explore the vario
    4 min read
    select command in Linux with examples
    select command in Linux is used to create a numbered menu from which a user can select an option. If the user enters a valid option then it executes the set of command written in select block and then ask again to enter a number, if a wrong option is entered it does nothing. If user enters nothing and simply press 'enter' the option menu gets print
    1 min read
    atrm command in Linux with examples
    atrm command is used to remove the specified jobs. To remove a job, its job number is passed in the command. A user can only delete jobs that belong to him. Only superuser can delete any job even if that belongs to another user. Syntax: atrm [-V] job [job...] Options: -V : Used to print the version number atrm -V job : Job number of the job which i
    1 min read
    comm command in Linux with examples
    comm compare two sorted files line by line and write to standard output; the lines that are common and the lines that are unique. Suppose you have two lists of people and you are asked to find out the names available in one and not in the other, or even those common to both. comm is the command that will help you to achieve this. It requires two so
    5 min read
    cmp Command in Linux with examples
    cmp command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out whether the two files are identical or not. When cmp is used for comparison between two files, it reports the location of the first mismatch to the screen if difference is found and if no difference is found i.e the files compared are identical.cmp dis
    5 min read
    expand Command in LINUX with examples
    Whenever you work with files in LINUX there can be a situation when you are stuck with a file containing many tabs and whatever you need to do with a file requires that file with no tabs but with spaces. In this situation, the task looks quite simple if you are dealing with a small file but what if the file you are dealing with is very big or you n
    3 min read
    df Command in Linux with examples
    There might come a situation while using Linux when you want to know the amount of space consumed by a particular file system on your LINUX system or how much space is available on a particular file system. LINUX being command friendly provides a command line utility for this i.e df command that displays the amount of disk space available on the fi
    8 min read
    help Command in Linux with examples
    If you are new to LINUX operating system and having trouble dealing with the command-line utilities provided by LINUX then you really need to know first of all about the help command which as its name says help you to learn about any built-in command. help command as told before just displays information about shell built-in commands. Here's the sy
    3 min read
    fgrep command in Linux with examples
    The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also to be searched. This command is useful when you need to search for strings which contain lots of regular expression metacharacters, such as "^", "$", etc. Syntax: fgrep [options] [ -e pattern_list] [pattern] [file] Options with Description
    3 min read
    rcp Command in Linux with examples
    There comes a time while using LINUX when there is a need to copy some information stored in a file to another computer. This can be done simply using rcp command line utility . Obviously there exists some other methods to complete the above mentioned task which are more secure (like scp or rsync) but this command lets you do this in the simple way
    4 min read
    fmt command in Linux with examples
    fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be really time-consuming when it comes to large text files, this is where fmt comes to rescue. fmt re-formats each paragraph in the file specified, writing to standard output. Here's the syntax
    4 min read
    unexpand command in Linux with Examples
    To convert the leading spaces and tabs into tabs, there exists a command line utility called unexpand command. The unexpand command by default convert each spaces into tabs writing the produced output to the standard output. Here's the syntax of unexpand command : Syntax : $unexpand [OPTION]... [FILE]... where, OPTION refers to the options compatib
    2 min read
    basename Command in Linux with examples
    basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed. Using basename command : The basename command can be easily used by simply writing basename followed by the file name or the full pathname. Syntax of basename command : $basename NAME [SUFFIX] or $basen
    3 min read
    uniq command in Linux with examples
    The linux uniq command is basically used to remove all repeated lines in a file. This command is used when a line is repeated multiple times and replace these multiple lines with one line. This command is designed to work on sorted files. Purpose : Remove repetitious lines from the sorted 'input-file' and send unique lines to the 'output-file'. If
    2 min read
    anacron command in linux with examples
    anacron command is used to execute commands periodically with a frequency specified in days. Its main advantage over cron is that it can be used on a machine which is not running continuously. In cron if a machine is not running on time of a scheduled job then it will skip it, but anacron is a bit different as it first checks for timestamp of the j
    3 min read
    for command in Linux with Examples
    for command in Linux is used to repeatedly execute a set of command for every element present in the list. Syntax: for NAME [in WORDS ... ] ; do COMMANDS; done Example: Options: help for : It displays help information.
    1 min read
    exit command in Linux with Examples
    exit command in linux is used to exit the shell where it is currently running. It takes one more parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns the status of last command that is executed. Syntax: exit [n] Options for exit command - exit: Exit Without Parameter After pressing enter, the
    1 min read
    autoheader command in Linux with Examples
    autoheader command in Linux is used to create a template file of C "#define" or any other template header for configure to use. If the user will give autoheader an argument, it reads the standard input instead of reading configure.ac and also writes the header file to the standard output. This command scans the configure.ac file and figures out whi
    1 min read
    expect command in Linux with Examples
    expect command or scripting language works with scripts that expect user inputs. It automates the task by providing inputs. // We can install expect command using following if not installed // On Ubuntu $sudo apt install expect // On Redhat based systems $ yum install expect First we write a script that will be needing inputs from users and then we
    2 min read
    cal command in Linux with Examples
    If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal command shows the current month calendar as output. cal command is a calendar command in Linux which is used to see the calendar of a specific month or a whole year. Syntax: cal [ [ month ] year] The rectangular bracket means it is op
    2 min read
    function command in Linux with examples
    The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient. The function can be created in the user's current shell session or saved in the shell
    2 min read
    fg command in Linux with examples
    fg command in linux used to put a background job in foreground. Syntax: fg [job_spec] job_spec may be: %n : Refer to job number n. %str : Refer to a job which was started by a command beginning with str. %?str : Refer to a job which was started by a command containing str. %% or %+ : Refer to the current job. fg and bg will operate on this job if n
    1 min read
    bg command in Linux with Examples
    bg command in linux is used to place foreground jobs in background. Syntax: bg [job_spec ...] job_spec may be: %n : Refer to job number n. %str : Refer to a job which was started by a command beginning with str. %?str : Refer to a job which was started by a command containing str. %% or %+ : Refer to the current job. fg and bg will operate on this
    1 min read
    Clear Command in Linux with Examples
    clear is a standard Unix computer operating system command that is used to clear the terminal screen. This command first looks for a terminal type in the environment and after that, it figures out the terminfo database for how to clear the screen. And this command will ignore any command-line parameters that may be present. Also, the clear command
    2 min read
    Continue Command in Linux with examples
    continue is a command which is used to skip the current iteration in for, while, and until loop. It is used in scripting languages and shell scripts to control the flow of executions. It takes one more parameter [N], if N is mentioned then it continues from the nth enclosing loop. The syntax for the `continue` command in Linuxcontinue or continue [
    2 min read
    hostid command in Linux with examples
    hostid is a command in Linux that is used to display the Host's ID in hexadecimal format. It provides a quick and straightforward way to retrieve the host ID, allowing administrators to associate it with software licenses or perform system-specific operations. Syntax of `hostid` command in Linuxhostid [OPTION] Options provided by hostedhostid --hel
    1 min read
    Dirname Command in Linux with Examples
    dirname is a command in Linux that is used to remove the trailing forward slashes "/" from the NAME and prints the remaining portion. If the argument NAME does not contain the forward slash "/" then it simply prints dot ".". In other words, we can say that the `dirname` command is a useful tool for extracting the directory portion from a given path
    2 min read
    sdiff command in Linux with Examples
    sdiff command in linux is used to compare two files and then writes the results to standard output in a side-by-side format. It displays each line of the two files with a series of spaces between them if the lines are identical. It displays greater than sign if the line only exists in the file specified by the File2 parameter, and a | (vertical bar
    2 min read
    Groups Command in Linux With Examples
    In Linux, there can be multiple users (those who use/operate the system), and groups are nothing but a collection of users. Groups make it easy to manage users with the same security and access privileges. A user can be part of different groups. The `groups` is a powerful tool that helps administrators to view the group memberships of a user and re
    2 min read
    three90RightbarBannerImg