0

Let's say you have the following input file

Some text. It may contain line
breaks.

Some other part of the text

Yet an other part of
the text

And you want to iterate each text part (seperated by two line breaks (\n\n)), so that in the first iteration I would only get:

Some text. It may contain line
breaks.

In the second iteration I would get:

Some other part of the text

And in the last iteration I would get:

Yet an other part of
the text

I tried this, but it doesn't seem to work because IFS only supports one character?

cat $inputfile | while IFS=$'\n\n' read part; do
  # do something with $part
done

2 Answers 2

2

This is the solution of anubhava in pure bash:

#!/bin/bash

COUNT=1; echo -n "$COUNT: "
while read LINE
do
    [ "$LINE" ] && echo "$LINE" || { (( ++COUNT )); echo -n "$COUNT: " ;}
done
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using a variation of this (without COUNT), because I had escape issues with the awk solution. My text parts contained a lot of characters like ' or " and needed to be passed to an other script via the system() call.
2

Use awk with null RS:

awk '{print NR ":", $0}' RS= file
1: Some Text. It may contains line
breaks.
2: Some Other Part of the Text
3: Yet an other Part of
the Text

You can clearly see that your input file has 3 records now (each record is printed with record # in output).

8 Comments

How can I iterate over that with a while or a for loop, like shown in the question?
With awk you don't need to iterate in a loop since awk processes input record by record. You can anything with each record (denoted by $0) and file be iterated by awk
oops, didn't see your answer...posted a dup ... :( +1 and remove mine.
@Kent: Thanks so much. It is the same idea as your answer, just happened to post it few minutes earlier.
I don't know awk too well. I need to execute other shell scripts for each record. Can that be done with awk?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.