Splitting fixed length file using awk

Hi,
I need to split a fixed length file of 160 characters based on value of a column. Example:

ABC   456780001 DGDG SDFSF
BCD   444440002 SSSS TTTTT
ABC   777750003 HHHH UUUUU
THH   888880001 FFFF  LLLLLL
HHH   999990002 GGGG OOOOO

I need to split this file on basis of column from position 12-15 i.e 0001,0002,0003 and copy the data to files 0001.txt,0002.txt,0003.txt.

so 0001.txt should contain

ABC   456780001 DGDG SDFSF
THH   888880001 FFFF  LLLLLL

002.txt should contain

BCD   444440002 SSSS TTTTT
HHH   999990002 GGGG OOOOO

003.txt should contain

ABC   777750003 HHHH UUUUU

and all the new files should have same fixed width as the original file.

Kindly help how can i achieve this.:wall:

awk '{ F=substr($0,12,4) ".txt"; print $0 >> F; close(F) }' file
1 Like

Thanks Yoda. It is working fine.

Can you also tell me how can i append the file name with a parameter. Something like 0001_RL_$1.txt. $1 being passed as an arguement.

or else if $1 can be picked up from file itself from position 60-64.

awk -v A="$1" '{F=substr($0,12,4) "_RL_" A ".txt"; print $0 >> F; close(F) }' file

superb..
thanks a lot..

stealing Yoda's code:

awk '{F=substr($0,12,4) "_RL_" substr($0,60,5) ".txt"; print $0 >> F; close(F) }' file

Hi,
I am facing one issue here. The command works fine if i hardcode the file name but if is pass it as an arguement it doesn't work. For e.g:Below commands works fine

awk -v A="$type" '{F=substr($0,23,8) "_LTD_" A ".txt"; print $0 >> F; close(F) }' RL004.txt

But the below command does not work.

awk -v A="$type" '{F=substr($0,23,8) "_LTD_" A ".txt"; print $0 >> F; close(F) }' $path/$filename 

Can you please help with this.

awk:

awk '{
  id=substr($0,12,4)
  file=sprintf("%s.txt",id)
  print $0 >> file
}' a

python:

dict={}
with open("a.txt") as f:
 for line in f:
  id=line[11:15]
  line=line.replace("\n","")
  dict.setdefault(id,[]).append(line)
for i in dict:
 f=i+".txt"
 with open(f,"w") as ff:
  for l in dict:
   print(l,file=ff)