Home > Enterprise >  Using awk to append to the row above the current
Using awk to append to the row above the current

Time:07-19

I have a text files where the some text from the first field rolls over onto the next row.

Example

Company Name LLC
Company Name2
LLC
Very Good company name but rolls
over

I am able to get the rows that have rolled over by

awk '{ if (NF ==1) print $0}'

I am looking for a way to append the text onto (NR -1)

correct output

Company Name LLC
Company Name2 LLC
Very Good company name but rolls over

CodePudding user response:

awk 'NR>1{ORS=(NF>1?OFS:"\n")} 1' input_file

CodePudding user response:

Preliminarily, you are not making use of awk's pattern-action syntax and defaults; awk NF==1 has the same effect as the command you posted.

But for your Q, in awk you need to buffer the previous line and then decide how to use it:

awk 'NF==1{print p,$0; p=""; next} length(p){print p} {p=$0} END{print p}'

Or less efficiently but simpler you can do

tac | awk 'NF==1{getline t; print t,$0; next} 1' | tac

CodePudding user response:

With your shown samples and attempts please try following tac awk code.

tac Input_file | 
awk '
NF==1{
  val=$0(val?OFS val:"")
  next
}
NF>1{
  print $0,val
  val=""
}' | 
tac
  • Related