Hind Forsum
Hind Forsum

Reputation: 10527

Using bash: how to split file according to input file line content?

I've got some big text log files. The content is like:

Begin to work
Load library
Start
TEXTLOG
Checking
ok
TEXTLOG
Start process
Starting node
ok
TEXTLOG
Stop node
TEXTLOG

In this file the lines "TEXTLOG" serves as delimeter, so I wish to split this file into several smaller files, using "TEXTLOG" as EOF indicator, so I should files:

file1:

Begin to work
Load library
Start

file2:

Checking
ok

file3:

Start process
Starting node
ok

file4:

Stop node

How can I achieve this using shell? Thanks.

Upvotes: 1

Views: 58

Answers (3)

Mats Faugli
Mats Faugli

Reputation: 169

Using csplit:

csplit --suppress-matched file "/TEXTLOG/" "{*}"
  • --suppress-matched makes sure the TEXTLOG separator is not included in the output
  • "{*}" tells csplit to run the matching pattern not just once, but throughout the entire file

Upvotes: 2

oliv
oliv

Reputation: 13259

Using GNU awk:

awk -v RS="\nTEXTLOG\n" '{print > "file"++c}' file

RS is the record separator and allows to get the content of each file at once.

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 185831

Try this :

awk 'BEGIN{c=1}/^TEXTLOG/{c++;next} {print > "file"c}' file 
ls 

Upvotes: 1

Related Questions