How to Use sed to Remove Leading Whitespaces in File


Often you may want to use sed to remove all leading whitespaces from each line in a file.

You can use the following basic syntax to do so:

sed 's/^[[:space:]]*//' team_names.txt

This particular example will remove all leading whitespaces from each line in the file named team_names.txt.

Here is what the various sed commands do:

  • s: Used to substitute one pattern for another
  • ^[[:space:]]*: Matches the start ( ^ ) of the string along with all whitespace that follows the start
  • //: Replaces the whitespaces at the start with nothing, which effectively removes the leading whitespaces

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

Example: Use sed to Remove Leading Whitespaces in File

Suppose that we have a file named team_names.txt that contains the names of various basketball teams.

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

We can see that several lines in the file have leading whitespaces at the beginning of the line.

We can use the following syntax to remove the leading whitespaces from each line:

sed 's/^[[:space:]]*//' team_names.txt

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

sed remove leading whitespace

Notice that the leading whitespaces have been removed from each line.

Note that if you would like to save these changes to the file in-place then you can add the -i flag as follows:

sed -i 's/^[[:space:]]*//' team_names.txt 

This will save the changes to the team_names.txt file in-place.

Related Tutorials

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

How to Use sed to Print Out Line Numbers
How to Use sed to Print Specific Lines in File
How to Use sed to Print Every nth Line of File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply