How to split a data file into separate files with the file names depending upon a column's value?

Hi,
I have a data file xyz.dat similar to the one given below,

2345|98|809||x|969|0
2345|98|809||y|0|537
2345|97|809||x|544|0
2345|97|809||y|0|651
9685|98|809||x|321|0
9685|98|809||y|0|357
9685|98|709||x|687|0
9685|98|709||y|0|234
2315|98|809||x|564|0
2315|98|809||y|0|537
2315|98|809||x|523|0
2315|98|809||y|0|535

I need to split the file into seperate file with the condition that :
1) All the rows which has the same value in column 1 should be in one file.
2) The name of the file should be starting with the column 1's value.

ie:
2345_xyz.dat should be created and it should contain only the below data:
2345|98|809||y|0|537
2345|97|809||x|544|0
2345|97|809||y|0|651

9685_xyz.dat should be created and it should contain only the below data:
9685|98|809||x|321|0
9685|98|809||y|0|357
9685|98|709||x|687|0
9685|98|709||y|0|234

2315_xyz.dat should be created and it should contain only the below data:
2315|98|809||x|564|0
2315|98|809||y|0|537
2315|98|809||x|523|0
2315|98|809||y|0|535

Also the main data file xyz.dat should not be removed.

Hi, try this:

awk -F\| '{n=$1"_xyz.dat"}f!=n{close(f);f=n}{print>f}' file
1 Like
awk -F\| '{print > $1"_xyz.dat"}' inputfile
1 Like