Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using sed to switch columns separated by tabs in a file? 2

Status
Not open for further replies.

goldenradium2001

Technical User
Mar 22, 2002
91
US
I am just trying a simple experiment with sed. I have a file with five columns with tabs as the delimiter called file1.

one two three four five
one two three four five
one two three four five

I want to switch columns one and two so that the file looks like:

two one three four five
two one three four five
two one three four five

I'm using the substitute command with the (.*\) syntax but am unable to figure out what command syntax to use.

Any help? Thanks.
 
Hi,
Why Sed? Why not awk?

awk '{printf(&quot;%s\t%s\t%s\t%s\t%s\n&quot;,$2,$1,$3,$4,$5);}' <file>
 
But if you insist on using sed, try this
Code:
sed &quot;s/\([^<tab>]*\)<tab>\([^<tab>]*\)/\2<tab>\1/&quot; file
CaKiwi
 
Directed to CaKiwi and tdatgod...or anyone who wants to answer...thanks!

GREAT! Those two commands work wonderfully. Do you have any references that explain what those characters do in laymen terms? I can figure out some of it...I think.

Thanks.
 
nevermind, i sort of figured it out. what you are doing is capturing a non tab character then saving each captured item to 1 and 2 in the order in which it was captured. then reverse the order by using the number of each saved string in the order that you want. this is for the sed command though.

i'm still not in awk mode yet.

Thanks!
 
Awk by default separates the line into tokens delimited by FS ( field separator ) which defaults to white space ( tabs and spaces ) Every token is then numbered. ( $1, $2, $3 ... )

If you want to specify a different delimiter like ':' you can change the FS character.

BEGIN {FS=&quot;:&quot;}

or use the -F option on the command line.

-F ':'



the printf( ) just reformats what you want AWK to output.

%s means write it out a string

%s is good because even numbers are nothing more than a string if you don't intend on doing arithmetic on them.

the \t is shorthand for a TAB character. I figure if you had a TAB delimited file to start with you would want a TAB deleimited file on the other side.

the \n is the EOL character.



you might want to review the man page for 'ed' the line editor which has a discusion of regular expression conventions used in the above SED example.

---

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top