Splitting file into multiple files and renaming them

Hi all,

Newbie here. First of all, sorry if I made any mistakes while posting this question in terms of rules. Correct me if I am wrong. :b:

I have a .dat file whose name is in the format of 20170311_abc_xyz.dat. The file consists of records whose first column consists of multiple dates in the format 2017-03-11.

I want to split this file "20170311_abc_xyz.dat" into multiple files based on the first column. The output files must consist of records which are grouped by the individual dates.

I was able to achieve the same using awk command. Below is the code I used for it.

awk -F\| '{print>$1(-F\-)"_abc_xyz.dat"}' 20170311_abc_xyz.dat

I got it from a forum. The due credits for the above code goes to the one who did it.

The problem now is the files created after splitting are coming in the name format: 2017-03-09_abc_xyz.dat
2017-03-10_abc_xyz.dat (Assuming that the first columns in my .dat file consists of the dates 2017-03-09 & 2017-03-10)

I want the files to be in the format 20170309_abc_xyz.dat & 20170310_abc_xyz.dat

Your help is much appreciated.
Thanks in advance. :slight_smile:

What do you expect that (-F\-) to do?
Try

awk  '{FN = $1 "_abc_xyz.dat"; gsub (/-/, "", FN);  print > FN }' file
1 Like

That worked like a charm. :b:
Thanks a lot!! :slight_smile: