Trix & Graphix

Columns to rows and vice versa in ASCII files

Imagine you have a table with data within an ASCII file. Let's asume your table is homogenious (otherwise you can take a look at this post. You may want to turn it into just one row, or just one column. I'm going to explain how to do it in two different ways using two different Unix tools: awk and tr.

- tr version:

This is the easiest way. In order to turn the file into just one row, the "\n" characters have to be removed. This can be done with the command:

tr "\n" " " < filein.asc > fileout.asc



Similarly, in order to turn the file into a column you can change the "\n" characters as field separator:

tr " " "\n" < filein.asc > fileout.asc



- awk version

Focusing now in the awk version, you can use

awk '{for(i=1;i<=NF;i++) print $i}' filein.asc > fileout.asc


in order to turn the file into a column, or

awk '{for(i=1;i<=NF;i++) printf "%s ", $i}' filein.asc > fileout.asc


to turn the file into just one row.

Easy, isn't?

1 Comment:

Anonymous said...

good start