Jan Rostenkowski
Jan Rostenkowski

Reputation: 325

How to copy different evenly spaced blocks of text from one file into multiple files containing each block

Let's say I have a text file like the following:

cheese
a b c 
d e f 
*

cheese
g h i 
j k l 
* 

cheese 
m n o 
p q r 
*
...

I wish to copy and append each block of text below the string cheese onto 3 other different files.

Meaning, let's say I have in files 1.txt, 2.txt and 3.txt in some directory.

Once appended, 1.txt should look like:

bla bla bla... 
a b c 
d e f 
* 

and 3.txt should look like:

bla bla bla...
m n o 
p q r 
*

Upvotes: 0

Views: 51

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133710

Could you please try following.

awk '
/cheese/{
  close(file)
  outfile++
  file=outfile".txt"
  next
}
{
  print > (file)
}
' Input_file

Explanation: Adding detailed explanation for above code.

awk '                   ##Starting awk program from here.
/cheese/{               ##Checking condition if line contains string cheese then do following.
  close(file)           ##Closing output file with close statement.
  outfile++             ##Increment variable outfile with 1 each time cursor comes here.
  file=outfile".txt"    ##Creating variable named file whose value is variable outfile and string .txt in it.
  next                  ##next will skip all further statements from here.
}
{
  print > (file)        ##Printing all lines into output file.
}
' Input_file            ##Mentioning Input_file name here.

Upvotes: 2

Related Questions