in reply to Re^4: String manipulation in a document
in thread Grep a particular text
Thank you for showing your code. To begin, several recommendations:
Now moving on to the question of how to search and replace text. First of all, reading from input files and writing to output files is described in "Files and I/O" in perlintro - I would recommend reading the whole document, since it's not very long and it gives a good overview of Perl.
As for the algorithm, there are several general approaches I'd consider:
In the following, I'm using a combination of the third and fourth points, but note that this code makes quite a few assumptions about your input file format, which you haven't shown a lot of. In your real script, you'd have to replace DATA with the filehandle you opened.
use warnings; use strict; local $/ = ""; my $buffer; while (<DATA>) { if ( s/\\section\{.*?\K(\\qr\{.*?\})(?=\})//i ) { $buffer .= $1; } elsif (defined $buffer) { s/^\S+\s+\S+\K/$buffer/; undef $buffer; } print; } print $buffer if defined $buffer; __DATA__ \section{Results\qr{text ... text}} Normal paragraph text here... \section{Funding\qr{text ... text}} Funding text here...
Output:
\section{Results} Normal paragraph\qr{text ... text} text here... \section{Funding} Funding text\qr{text ... text} here...
I'm really not sure how you choose the insertion point for the \qr{} - in the original question, it seems you wanted it inserted after the fourth word in the paragraph, while in this example, it looks like you wanted it inserted after the second word.
|
|---|