chas
chas

Reputation: 1645

split file using awk

I tried to split my file based on first column and write to separate txt file using the command found in one of the threads and it shows the following error:

awk '{print > $1".txt"}' TS129.txt 
awk: syntax error at source line 1
context is
{print > >>>  $1".txt" <<< 
awk: illegal statement at source line 1

It looks a simple error but it doesn't strike to my mind. Could someone help to fix this?

Upvotes: 2

Views: 2410

Answers (1)

Dimitre Radoulov
Dimitre Radoulov

Reputation: 27990

Try:

awk '{ print > ($1 ".txt") }' TS129.txt 

UPDATE:

awk '{
  close(fn)
  fn = $1 ".txt"
  print >> fn
  }' TS129.txt 

If you prefer to avoid calling close for every line:

awk '{
  seen[$1]++ || count++
  if (count >= limit) {
    for (fname in seen)
      close(fname ".txt")
    c = ""
    split("", seen)
    }
  print >> ($1 ".txt")
  }' limit=<number_of_open_files> TS129.txt 

Upvotes: 4

Related Questions