Bash: How to Remove First Word from Each Line in File


Often you may want to use Bash to remove the first word from each line in a particular file.

You can use the cut command with the following syntax to do so:

cut -d ' ' -f2- player_info.txt

This particular example will remove the first word from each line in the file named player_info.txt.

Here is what the various commands do:

  • cut: Specifies that we would like to “cut” certain portions of each line
  • -d: Specifies that the delimiter to be used is a space
  • -f2-: Specifies that we would like to extract field 2 (-f2) and all fields after () that field

By extracting all fields starting from the second field in the line, we are able to effectively “remove” the first word from each line.

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

Example: Use Bash to Remove First Word from Each Line in File

Suppose that we have a file named player_info.txt that contains the positions of basketball players on various teams.

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

Now suppose that we would like to remove the first word from each line in the file.

We can use the following syntax to do so:

cut -d ' ' -f2- player_info.txt

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

Bash remove first word from each line

Notice that the first word has been removed from each line.

Also note that you could use the > command to save these results to a new file:

cut -d ' ' -f2- player_info.txt > player_info_new.txt

This syntax would remove the first word from each line in the file named player_info.txt and save the results to a new file named player_info_new.txt.

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