Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .