Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to create different files from a single file

Status
Not open for further replies.

scottpeter

Programmer
Sep 23, 2003
28
0
0
US
I have a text file in the following format. It contains number of file names and the contents for those files. The file name is commented out with '//'.

//FILE1.txt
CONTENTS OF FILE1
//FILE2.txt
CONTENTS OF FILE2
//FILE3.txt
CONTENTS OF FILE3
//FILE10.txt
CONTENTS OF FILE10
//FILE11.txt
CONTENTS OF FILE11

I need to read FILE1_name in the comments, create a file called 'FILE1_name' and paste the contents of that file into the file 'FILE1_name'. Then I need to do the same for FILE2_name and so on till the end of the file.

Hence in the above case, I need to have the following 5 files in the end
FILE1.txt. This will contain 'CONTENTS OF FILE1'
FILE2.txt. This will contain 'CONTENTS OF FILE2'
FILE3.txt. This will contain 'CONTENTS OF FILE3'
FILE10.txt. This will contain 'CONTENTS OF FILE10'
FILE11.txt. This will contain 'CONTENTS OF FILE11'

Can somebody help with with how to achieve this.

Thanks,
Pete
 
A starting point:
awk '/^\/\//{out=substr($0,3);next}{print > out}' /path/to/input

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
I find it's safer to close the output file each time or else strange things happen... you run out of file handles, if I recall.

Code:
awk '/^\/\//{close(out); out=substr($0,3);next}{print > out}' /path/to/input

Annihilannic.
 
Good catch Annihilannic, here a safer way:
awk '/^\/\//{if(out)close(out); out=substr($0,3);next}{print > out}' /path/to/input

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Thanks PHV and Annihilannic. It is working perfect.

I had one more question. Can I print the name of each of these files as the first line(as a header commented out) of that respective file.

Thanks,
Pete

 
Certainly... perhaps we should leave that as an exercise for you (as a programmer) to figure out? :)

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top