Bash: How to Use ‘cut’ with Multiple Spaces


Often you may want to use the cut command in Bash to extract a specific field from a file, using multiple spaces as the delimiter.

You can use the following syntax to do so:

< teams.txt tr -s ' ' | cut -d ' ' -f2

This particular example extracts the second field from the file named teams.txt in which the fields in each line may be separated by one or more spaces.

Here is how this syntax works:

  • First, we use tr -s ‘ ‘ to “squeeze” all occurrences of multiple spaces into a single space
  • Then, we use cut -d ‘ ‘ to specify that a single space should be used as a delimiter
  • Lastly, we use -f2 to extract only field 2 from each line in the file

The following example shows how to use this syntax in practice.

Example: How to Use ‘cut’ with Multiple Spaces in Bash

Suppose that we have a file named teams.txt that contains information about various basketball teams.

We can use the cat command to view the contents of this file:

Notice that some lines have fields that are separated by multiple spaces.

Suppose that we would like to extract the second field from each line in the file.

We can use the following syntax to do so:

< teams.txt tr -s ' ' | cut -d ' ' -f2

The following screenshot shows how to use this syntax in practice:

Bash cut multiple spaces

Note that we’re able to extract the second field from each line in the file, despite the fact that the lines do not all have the same number of spaces that separate each field.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File

Leave a Reply