user1256539
user1256539

Reputation:

shell scripting: rearrange columns

I have a text file (tab separated) which consist of 17 column. I would like to change this structure in this way. Conserve column from 1 to 6, until the end of the file of course, and append column from 7 to 16 (I can get rid of the 17) one below each other and so repeat every the ones from 1 to 5 for each column that I added. This means that I will also need to add an extra column with same numbers until the next added start, in order to keep track of the column that I appended and see at which line it start.

Hope this is enough clear.

Thanks for yours precious time and support.

Original

179    1   AA     19.50    30.00  1.0000  2.0000  3.0000 ...  
180    1   BB     19.75    30.00  4.0000  5.0000  6.0000 ...  
230    1   CC     32.25    30.00  7.0000  8.0000  9.0000 ...  

Needed

179    1  1 AA     19.50     30.00  1.0000    
180    1  1 BB     19.75     30.00  4.0000    
230    1  1 CC     32.25     30.00  7.0000  
179    1  2 AA     19.50     30.00  2.0000   
180    1  2 BB     19.75     30.00  5.0000    
230    1  2 CC     32.25     30.00  8.0000   
179    1  3 AA     19.50     30.00  3.0000    
180    1  3 BB     19.75     30.00  6.0000    
230    1  3 CC     32.25     30.00  9.0000   

Upvotes: 1

Views: 692

Answers (1)

beny23
beny23

Reputation: 35038

How about this for an idea (using awk to pick out the column data, using temporary output files to hold the data):

rearrange.awk:

{
   for (i=6; i<=NF; ++i) {
      print $1, $2, (i-5), $3, $4, $5, $i > "temp_output"i".txt"
   }
}

Then this would be used in a script:

awk -f rearrange.awk < input.txt
cat temp_output*.txt > output.txt
rm temp_output*.txt

Upvotes: 1

Related Questions