Maxxx
Maxxx

Reputation: 3768

Command to replace single space with tabs in a text file

So i have a text file and the problem is that both spaces and tabs are used to separate column values which is causing me a lot of issue due to the inconsistency. For example:

ID Name    Class Time
1 Johnson  5-D 6pm
         .
         .
         .

As you can see in the example, both ID and Name are separated by single space while Name and Class are separated by a tab.

How do i write a sed command to replace all single space in the text file with a tab? I would want a new text file generated looking something like:

ID      Name      Class     Time
1       Johnson   5-D        6pm

The alignment doesn't matter at this point, i just want to replace the single space with tab.

Edit: awk script is welcomed too

Upvotes: 2

Views: 2854

Answers (4)

Shawn
Shawn

Reputation: 52334

Using perl to get its advanced regular expressions (In particular lookbehind and lookahead assertations to match a single space with no other whitespace on either side):

perl -pi -e 's/(?<=\S) (?=\S)/\t/g' input.txt

Upvotes: 0

Eraklon
Eraklon

Reputation: 4288

This might do the job sed -i -e 's/\s/\t/g' filename.txt.

Upvotes: 0

Freddy
Freddy

Reputation: 4688

With tr:

 tr ' ' '\t' <inputfile >outputfile

This replaces each space character with a tab.

If you should need this, you can also replace a sequence of multiple spaces with one tab using

 tr -s ' ' '\t' <inputfile >outputfile

Upvotes: 4

oliv
oliv

Reputation: 13239

Use column function:

column -t file

From man column:

-t   Determine the number of columns the input contains and create a table. Columns are
     delimited with whitespace, by default, or with the characters supplied using the -s
     option. Useful for pretty-printing displays.

Upvotes: 0

Related Questions