SaX SaX - 5 months ago 11
Perl Question

How to modify mutiple lines pattern?

I have in a file sth like:

....
sth
Q-[N1] your name?
A1-My first name is Joe
A2-My Last name is Jim
sth
sth
....
....
sth
Q-[N2] your name?
A1-My first name is Jack
A2-My Last name is JUNE
sth
sth
....


I wanted to add "last name" at the end of the line started with Q-.
Is it possible to do that in Perl,
sed
,
awk
,
grep
?
The transformed file looks like:

....
sth
Q-[N1] your name? **Jim**
A1-My first name is Joe
A2-My Last name is Jim
sth
sth
....
....
sth
Q-[N2] your name? **JUNE**
A1-My first name is Jack
A2-My Last name is JUNE
sth
sth
....

Answer

awk to the rescue! (with tac)

$ tac file | 
  awk '/My Last name is/{n=$NF} /^Q-/{$0=$0 FS "**"n"**"}1' | 
  tac

....
sth
Q-[N1] your name? **Jim**
A1-My first name is Joe
A2-My Last name is  Jim
sth
sth
....
....
sth
Q-[N2] your name? **JUNE**
A1-My first name is Jack
A2-My Last name is  JUNE
sth
sth
....