Operating System - Linux
1842549 Members
2499 Online
110189 Solutions
New Discussion

Re: Replace two lines with one using AWK

 
SOLVED
Go to solution
JUP
Regular Advisor

Replace two lines with one using AWK

Hi

I need to replace two lines with one. I tried SED but looks like SED does not accept Ctrl chars as input (eg. linefeed) as required for replacing the two lines.

I need to scan text files and replace the following:

#ifdef ABC
#123456

with

# Test


There is a carriage return between the #ifdef and the #123456.

Have tried with awk without any luck - can someone suggest how to do this.

Thanks in advance
JUP
3 REPLIES 3
NiCK_76
Respected Contributor

Re: Replace two lines with one using AWK

Hi,

sed -e 's/#ifdef ABC//g' -e 's/#123456/# Test/g' yourfilename


NiCK
just for fun
JUP
Regular Advisor

Re: Replace two lines with one using AWK

Thanks Nick

however your SED command leaves a blank line in the file. In total I wish to replace 4 lines with 1 so I will have 3 blank lines.

The only way to do this is with AWK - I have come up with this command but its not working. It is:


awk '{gsub("#ifdef ABC"\r\n#123456, "# Test"); print $0}' file.h > file.out


Does anyone know whats going wrong here ?

Thanks in advance
Stuart Browne
Honored Contributor
Solution

Re: Replace two lines with one using AWK

Awk is literally 'line-by-line'. It can't pattern match over multiple lines.

Perl can (although in my quick tests, I couldn't get it to work (phooey)), so this leaves doing it the hard way.

awk '
END {
print THIS
}
{
LAST=THIS
THIS=$0
if (SKIP == 1) {
SKIP=0
next
}
if ((LAST == "#ifdef ABC") && (THIS == "#123456")) {
print "#Test"
SKIP=1
} else {
print LAST
}
}' < yourfile

I'm sure there's a neater, shorter way out there though.
One long-haired git at your service...