0

I need to duplicate part of a plain text file as follows:

The text file consists of a sequence of "pages", of the form:

<page    [lots of lines of text]       /page>

<page    [lots of lines of text]       /page>

<page    [lots of lines of text]       /page>

<page    [lots of lines of text]       /page>

and I need an automated way to duplicate say the 3rd such "page". Is there an easy way to do this? (and similarly with "3rd" replaced by "23rd" etc)

Ideally I would like a bash script that unzipped the file, then did this duplication in the resulting text file, then rezipped it. The aim of this is a hack to get xournal to duplicate pages.

  • sorry, it's unclear for me. – Avinash Raj May 22 '14 at 14:03
  • sorry if its not clear: I want to search the text file for the third instance of "<page" and then copy all the text from there up to "page>", and paste all that in the text file just after the third "page>" – Phil168 May 22 '14 at 15:04
  • Is an awk solution acceptable? – steeldriver May 22 '14 at 15:31
  • sure that would be great – Phil168 May 22 '14 at 16:44
  • @Phil168: is text between `<page ../page> is multiline string or separate lines? – cuonglm May 22 '14 at 16:51
0

You should probably use a real markup parser for this, however interpreting your format description minimally as

<page line one
line two /page>
<page line three
line four /page>
<page line five
line six /page>

then if a quick'n'dirty awk solution1 is acceptable you could do

awk -v pagenum=2 'BEGIN {RS="/page>"; ORS=RS} FNR==pagenum {print} 1' file

or, less cryptically

awk -v pagenum=2 'BEGIN {RS="/page>"; ORS=RS}; FNR==pagenum {print}; {print}' file

where the number of the page you wish to duplicate is passed from the shell via the -v pagenum= parameter.


If there is 'stuff' after the last /page> tag the above expressions may treat it as an incomplete record and add a spurious closing /page> record separator. In that case, the following modified expression may work better

awk -v pagenum=2 'BEGIN {RS="/page>"; ORS=""; OFS=""} FNR==pagenum {print $0,RT} {print $0,RT}' file
  1. tested in gawk 3.1.8 and mawk 3.3
| improve this answer | |
  • Thanks a lot, that seems to work great (but it looks like black magic as you don't even seem specify the starting "<page"). I will read up on awk... – Phil168 May 22 '14 at 22:27
  • In fact this seems to add an extra "/page>" right at the end of the file. Is there a simple way to delete this? – Phil168 May 22 '14 at 22:46
  • Hmm.. I think that perhaps your file has a trailing blank line, which the awk expression is treating as an incomplete record - let me see if I can find a workaround – steeldriver May 22 '14 at 23:01

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.