0

I have a file as below.

***ABC***
Line1*
L*ine2*
***DEF***
Line3*
Lin*e4*

I need to create the 2 files ABC and DEF with the data below:

ABC.dat:

Line1*
L*ine2*

DEF.dat:

Line3*
Lin*e4*

I am ok to generate the file using small shell script as well.

4
  • I removed the * you were using since they were confusing the formatting. Are the * part of the file? How can we know which lines are the headers (the file names) and which the content? I mean, what's the difference between ABC and Line1? Is it every 3rd line? Is it lines with ALL CAPS? Please edit your question and clarify. Commented Apr 6, 2017 at 11:02
  • * is part of file. Each data line has final selimiter as *. Not every 3rd line. There will be indefinite number of lines between each pattern Commented Apr 6, 2017 at 11:33
  • OK, next time, please use the formatting tools to format your examples as code. So, can we assume that lines starting with *** will be the target file name? Commented Apr 6, 2017 at 11:45
  • Yes correct.... target file name will be the line starting with *** Commented Apr 6, 2017 at 11:51

1 Answer 1

2
$ awk '/^\*\*\*/{gsub(/\*/,""); fname=$0".dat"; next} {print > fname}' ip.txt 
$ cat ABC.dat 
Line1*
L*ine2*
$ cat DEF.dat 
Line3*
Lin*e4*
  • /^\*\*\*/ match lines starting with ***
    • gsub(/\*/,"") delete all * from such lines
    • fname=$0".dat" assign the remaining characters appended with .dat to fname variable
    • next move on to next line
  • print > fname print current line content to filename saved in fname

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.