Reputation: 3768
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
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
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
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