Register
It is currently Fri Oct 31, 2014 6:19 pm

bash script for file conversion format


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Tue Oct 05, 2010 12:02 pm   

Joined: Tue Oct 05, 2010 11:52 am
Posts: 2
Dear all,

I have a file in this format (like a matrix)
- A B C .. X
A 1 4 2 .. 2
B 2 6 4 .. 8
C 3 5 5 .. 4
. . . ... .
X . . ... .

and want to convert it into a file with this format:
A A = 1
A B = 4
A C = 2
...
A X = 2
B A = 2
B B = 6
etc

1) numbers and letters are separated with a tab
2) dots in the example represent numbers or letters

Is there an easy way in bash to make this conversion?

Thanks


Top
 Profile  
 PostPosted: Tue Oct 05, 2010 2:22 pm   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
I would try the following. It splits the first/header line into an 'header' array. For all other lines it splits the line into an 'arr' array and loops through all entries, printing the first column of the line, the appropriate header column and the column value.
Code:
awk '{
  if (NR == 1) { h = split($0, header, FS); }
  else {
    n = split($0, arr, FS);
    for (i=2; i<=(n>h?h:n); i++)
      printf("%s %s = %d\n", arr[1], header[i], arr[i]);
  }
}'


Top
 Profile  
 PostPosted: Fri Oct 08, 2010 6:42 am   
User avatar

Joined: Tue Apr 27, 2010 2:28 pm
Posts: 172
Location: Czech Republic
Pure bash:
Code:
{
    read -a header
    while read row ; do
        set ${row[@]}
        col=1
        rowname=$1
        shift
        for column ; do
            echo $rowname ${header[$col]} = ${!col}
            let col++
        done
    done
} < input


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 4 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP