awk / sed / etc. concatenating colums in one file

I wonder what is a simpler way to do this:

awk 'NR > 1 {print $1"\t"$2"\t"$3"\t"$4"\t"$5"\t"$6"\t"$7"\t"$8"\t"$9$10$11$12$13$14$15$16}'  file.in > file.out 

which is simply speaking " concatenate columns 9 to 16 by removing tabs in-between"

Merged columns 9-16 become "Notes" so may include whitespaces.

As of today there are 16 columns but this may evolve in more/less if required. Eventually column 9 (concatenated 9-16) becomes "notes" field.

Cheers,
Xi

Replay

Yep, many ways. I have tested the following two on a file created by:

perl -le 'next if $.==1; for(1..20){print join "\t",1..20 }' > file

That's a file with 20 lines and 20 tab-separated columns.

  1. Perl
    perl -F'\t' -ale '$"="\t";print "@F[0..7]",@F[8..$#F]' file
    
    

    Note that this joins all the fields from the 10th to the end. If you only want to join 9 to 16, use this instead:

    perl -F'\t' -ale '$"="\t"; print "@F[0..7]", @F[8..15], "\[email protected][16..$#F]"' file
    
    
  2. awk
    awk -F'\t' 'NR>1{
                    for(i=1;i<9;i++){
                        printf "%s\t",$i
                    }
                    for(i=9;i<=NF;i++){
                        printf "%s",$i
                    }print ""
                }' file
    
    

    As before, this will join all columns after the 10th. If you only want to join 9 to 16, use this instead:

    awk -F'\t' 'NR>1{
                    for(i=1;i<9;i++){
                        printf "%s\t",$i
                    }
                    for(i=9;i<=16;i++){
                        printf "%s",$i
                    }
                    for(i=17;i<=NF;i++){
                        printf "\t%s", $i
                    }
                    print ""
                }' file
    
    

Granted, the awk solutions aren't very short, but at least you don't need to specify all the fields by hand.

Assuming a few lines of tably separated values, generated thusly:

% perl -E 'say join "\t", 1..8 for 1..3'

The various columns can then be dealt with as necessary via the appropriate flags and variables and functions available in Perl.

% perl -E 'say join "\t", 1..8 for 1..3' \
| perl -pale '$_=join "\t", @F[0..3], join "", @F[4..7] if $. > 1'
1   2   3   4   5   6   7   8
1   2   3   4   5678
1   2   3   4   5678
%

Category: shell script Time: 2016-07-28 Views: 1

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.141 (s). 12 q(s)