LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk command to split file (https://www.linuxquestions.org/questions/linux-newbie-8/awk-command-to-split-file-580141/)

Hebron 08-27-2007 07:59 AM

awk command to split file
 
Hello, I have a file containing more than 200 columns. I need to split in into 2 files, both containing a little more than 100 column. I know you can use the command: awk '{print $1,$2, etc}' < input file > output file But doing it like this mean I have to type in all colums in the command ($1,$2,$3 etc). Is there a way to split the files into a certain amount of columns by giving a range in the command? Many thanks for help!!

Agrouf 08-27-2007 08:32 AM

cut -f -100
cut -f 100-
man cut

lakris 08-27-2007 08:54 AM

Could You try this:
If tab separated
Quote:

cut -f -100 file > first
cut -f 101- file > second
or, if space separated
Quote:

cut -d" " -f -100 file > first
cut -d" " -f 101- file > second
haven't tried it myself yet...

Tinkster 08-27-2007 07:35 PM

Or, if the separator can be either SPACE or TAB (or both
plus something else), in awk
Code:

BEGIN{
  FS="add your separator(s) of choice"
  numf=numFields
}
{
  for(i=1;i<=NF;i++) {
    if(i <= numf) {
      printf "%s ", $i >> "file1"
      if(i==numf){
        printf "\n" >> "file1"
      }
    } else {
      printf "%s ", $i >> "file2"
      if(i==NF){
        printf "\n" >> "file2"
      }
    }
  }
}

Save as something.awk

Run like so:
Code:

awk -v numFields=102 -f something.awk your-file
Untested, as always, and w/o any warranty.


Cheers,
Tink


All times are GMT -5. The time now is 11:33 AM.