Combine multiple lines between flags in one line in AWK

Viewed 386
5 Answers

Have your awk program in this way, written and tested in GNU awk.

awk '
/Pattern 2/{
  if(found){
    print val
  }
  found=""
  next
}
/Pattern 1/{
  found=1
  next
}
found{
  val=val $0
}
'   Input_file

Explanation: Adding detailed explanation for above.

awk '                      ##Starting awk program from here.
/Pattern 2/{               ##Checking if Pattern 2 is found here then do following.
  if(found){               ##Checking if found is set then do following.
    print val              ##Printing val here.
  }
  found=""                 ##Nullifying found here.
  next                     ##next will skip all statements from here.
}
/Pattern 1/{               ##Checking if Pattern 1 is found in current line.
  found=1                  ##Setting found to 1 here.
  next                     ##next will skip all statements from here.
}
found{                     ##Checking condition if found is SET then do following.
  val=val $0               ##Creating val variable here which is keep adding current line values in it.
}
'  Input_file              ##Mentioning Input_file name here. 

You may use this awk:

awk '/Pattern 2/ {if (s!="") print s; s=f=""} f {s = s $0} /Pattern 1/ {f=1}' file

AAAAAAAAAABBBBBBBBBB

And also with awk:

awk -v RS= '!/Pattern/ {sub(/\n/,"");print}' file
AAAAAAAAAABBBBBBBBBB

With GNU awk for multi-char RS and assuming your "Pattern"s really to take up whole lines and can't occur elsewhere in your input (easy fix if that's wrong):

$ awk -v RS='Pattern 2' 'sub(/.*Pattern 1/,""){gsub(/\n/,""); print}' file
AAAAAAAAAABBBBBBBBBB

or with any awk:

awk 'f{ if (/Pattern 2/){print buf; f=0} else buf=buf $0 } /Pattern 1/{f=1; buf=""}' file
AAAAAAAAAABBBBBBBBBB

You can set the output record separator to an empty string by using -v ORS=:

awk -v ORS= '/Pattern 1/{flag=1; next} /Pattern 2/{flag=0} flag' file

See an online demo.

To print a newline at the end, add END{print "\n"}:

 awk -v ORS= '/Pattern 1/{flag=1; next} /Pattern 2/{flag=0} flag; END{print "\n"}' file > newfile

See the Ubuntu 18 screenshot:

enter image description here

Related