How to Use sed to Replace Tab Characters


Often you may want to use sed to replace tab characters in a string.

Typically we use \t to reference tab characters but not all versions of sed recognize \t as a tab.

To ensure that you’re able to replace tab characters, you can use the following syntax:

sed "s/$(printf '\t')/-/g" athletes.txt

By using printf we are able to print a literal tab character in the code.

This particular example replaces all occurrences of tabs with a dash in the file named athletes.txt.

Note that we used the s command to “substitute” one pattern for another and we used the g command to make this substitution “globally”, i.e. for all occurrences.

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

Example: How to Use sed to Replace Tab Characters

Suppose that we have a file named athletes.txt that contains information about the team name and position of various basketball players.

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

Notice that the team name and position on each line is separated by a tab.

Suppose that we would like to replace the tab on each line with a dash instead.

We can use the following syntax to do so:

sed "s/$(printf '\t')/-/g" athletes.txt

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

sed replace tab character in file

Notice that the tabs on each line have been replaced with dashes instead.

Note that you can choose to replace the tabs with any pattern that you would like.

For example, you could use the following syntax to replace each tab with a colon and a space:

sed "s/$(printf '\t')/: /g" athletes.txt

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

sed replace tab with another pattern

Notice that the tabs on each line have been replaced with a colon and a space instead.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply