mmg
mmg

Reputation: 69

how to use awk to filter newline as record seperator and field seperator

I have the following file :

Field1

   UNIX - System V

Field2

   32 bit

Field3

   No

here field operator is double line and record operator is also a double line. I want output as:

Field1  UNIX - System V
Field2 32 bit

On writing the following command:

awk 'BEGIN{ FS="\n"; RS="\n\n"} {print $1 $2}' ctemp.txt

I am not getting my desired output.

Upvotes: 2

Views: 159

Answers (2)

Ed Morton
Ed Morton

Reputation: 204124

$ awk 'NF{printf "%s%s", $0, ((++c)%2 ? OFS : ORS)}' file
Field1    UNIX - System V
Field2    32 bit
Field3    No

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133650

1st solution: Could you please try following, tested with provided samples and written with GNU awk.

awk -v FS="\n" -v RS="^$" '{for(i=1;i<=NF;i+=4){print $i,$(i+2)}}' Input_file


2nd solution: OR above will NOT deal with spaces coming in starting of lines, in case you want to remove those spaces like we have before (UNIX - System V) then try following.

awk -v FS="\n" -v RS="^$" '
BEGIN{
  OFS="\t"
}
{
  for(i=1;i<=NF;i+=4){
    sub(/^ +/,"",$i)
    sub(/^ +/,"",$(i+2))
  print $i,$(i+2)
  }
}
'  Input_file


3rd solution: Should work in a NON GNU awk too, tested and written with provided samples by OP.

awk '
value==""{
  value=$0
  next
}
NF && value{
  sub(/^ +/,"")
  print value,$0
  value=""
}
'  Input_file

Upvotes: 1

Related Questions