-1

I have stdout with lots of blocks of text that look something like this:

% QUESTION
Who played drums for The Beatles?


% QUESTION
Who played
guitar

for The Beatles?


% QUESTION
Who played

bass for The Beatles

?

The idea here is that the file is divided into "chunks" where each chunk begins with the line % QUESTION. I'd like to write a script that will print the nth chunk of this data.

For example, issuing nthchunk 3 should print

Who played

bass for The Beatles

?

How could I go about doing this?

1
  • Genuinely curious why the downvote. Is there something wrong with this question? Jan 5, 2021 at 21:58

3 Answers 3

6

With the awk implementations that support a regexp as their record separator (RS) such as GNU awk, you could do:

awk -v n=3 -v RS='(\n+|^)% QUESTION\n' 'NR == n+1 {print; exit}' < questions.txt
0

GNU sed employing the extended regex mode -E will be used to solve this problem. Basic idea is to accumulate the consecutive % question lines and the lines in between in the pattern space. Whilst the counter is kept in the hold space as a string of dots.

chunk=2
sed -E ':loop
  /%/,/%/N
  /%.*%/!{
    /%/!d;$!bloop
    s/$/\nfiller/
  }
  G;s/$/./
  /\n[.]{'"${chunk}"'}$/bend
  h;s/.*\n//;x
  s/.*(\n.*)\n.*$/\1/;D
  :end
  s/^[^\n]*\n+(\S.*\S)(\n.*){2}$/\1/
  q
' file

Alternatively, perl in slurp mode with FS set to question lines. The array @F's elements shall be the chunks.

perl \
  -F'/(?:^|\n+)\%\h+QUESTION\n+/' \
  -pals -0777 \
  -e '$_=$F[$n]' \
-- -n="${chunk}" ./file;

Output:

Who played
guitar

for The Beatles?
0

I'd like to write a script that will print the nth chunk of this data.

Setting RS and ORS, you can get each question this way for example:

it requires GNU awk for multi-char RS

awk -v RS='% QUESTION'  -v ORS='' '/\<drums\>/ {print $0}' file

Who played drums for The Beatles?
  • or bass
awk -v RS='% QUESTION'  -v ORS='' '/\<bass\>/ {print $0}' file

Who played

bass for The Beatles

?
  • or guitar:
awk -v RS='% QUESTION'  -v ORS='' '/\<guitar\>/ {print $0}' file

Who played
guitar

for The Beatles?
  • or using a number for chunk instead
$ nchunk=3
awk -v nchunk="$nchunk" -v RS='% QUESTION'  -v ORS=''  'NR==nchunk+1 {print $0}' file

Who played

bass for The Beatles

?
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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