Operating System - HP-UX
1748205 Members
3881 Online
108759 Solutions
New Discussion юеВ

append current line to previous line if current line matches pattern

 
SOLVED
Go to solution
Franky Leeuwerck_2
Super Advisor

append current line to previous line if current line matches pattern

Hi everyone,

I have a scripting question.

My source file contains lines like :
data...xb
data...95
Query:...ab
data...ab
data...a5
data...7c
data...d5
Query:...cd
data...e5

The desired output should look like :
data...95 Query:...ab
data...d5 Query:...cd

In other words, I need all lines followed by a ' Query;' line, appended with its following ' Query:' line.

Can this be done in a one-liner ?

Thanks in advance for your help.
Franky
6 REPLIES 6
Nicolas Dumeige
Esteemed Contributor

Re: append current line to previous line if current line matches pattern

My awk version :
nawk 'BEGIN { CURRENT="" } { OLD=CURRENT ; CURRENT=$0 } { if ( match(CURRENT,"Query") ) { printf("%s %s\n",OLD, CURRENT) } }' you_file
All different, all Unix
Franky Leeuwerck_2
Super Advisor

Re: append current line to previous line if current line matches pattern

Thanks for your quick reply Nicolas, but nawk is not available on this system. I have only user rights on it.

Franky
Jean-Luc Oudart
Honored Contributor
Solution

Re: append current line to previous line if current line matches pattern

well close to the one line :

awk '{
if(substr($0,1,5)!="Query") line=$0; else print line,$0; }'

run =>
data...95 Query:...ab
data...d5 Query:...cd

Regards,
Jean-Luc
fiat lux
Franky Leeuwerck_2
Super Advisor

Re: append current line to previous line if current line matches pattern

Jean-Luc,

Thanks ... thanks ...

This is what I need.

Regards,

Franky
Nicolas Dumeige
Esteemed Contributor

Re: append current line to previous line if current line matches pattern

Using the good old awk :

awk 'BEGIN { CURRENT="" } { OLD=CURRENT ; CURRENT=$0 } { if ( substr(CURRENT,1,5)=="Query" ) { printf("%s %s\n",OLD, CURRENT) } }'
All different, all Unix
Franky Leeuwerck_2
Super Advisor

Re: append current line to previous line if current line matches pattern

Ok Nicolas,

This one works too for me.

Thanks.

Franky

"over and out"