Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have text file like this

1. some topic
a
20p
ID: 20


2. something topic
another
here
there
ID: 30


3. ...
here
come
another
ID: 40

They are separate by two newlines. How could I split this into separate files? The split could use ID as well, but most examples I have seen so far use patterns as the header of a new file. Anything using perl python or a shell script is fine.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

It's simple automaton:

 #!/bin/sh

 state=text

 cat | while read line; do

    if [ "$state" == "text" ]; then
        if [ "$line" == "" ]; then
            state="oneline"
        fi
    elif [ "$state" == "oneline" ]; then
        if [ "$line" == "" ]; then
            state="twolines"
        else
            state="text"
        fi
    else
        echo "switch file here"
        state="text"
    fi

    echo $line

 done

You can switch files or do whatever you want on line "switch file here".

share|improve this answer
    
Ah thanks. I replace swith file here with simple counter and pipe everything from echo $line to file. Work like charm. –  yumyai Nov 22 '11 at 22:09

Using Ruby:

IO.read("somefile.txt").strip.split("\n\n\n").each_with_index do |e, i|
  z = e.split("\n", 2)
  next unless z.size == 2
  File.open("#{i}-#{z[0]}.txt", "w") { |f| f.write(z[1]) }
end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.