1

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.

2 Answers 2

2

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

1
  • Ah thanks. I replace swith file here with simple counter and pipe everything from echo $line to file. Work like charm.
    – yumyai
    Nov 22, 2011 at 22:09
1

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

You must log in to answer this question.

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