awk Help: Horizontal to Vertical print with pattern match

Hi AWK Experts,

Following is the data :

BRH113 DD AA HH CA DD DD AA HH BRH091 A4 A6 AH H7 67 HH J8 9J BRH0991 AA D8 C23 V5 H7 BR2 BRH991 AA HH GG5 BT0 JJ0

I want the output to be alligned with the pattern matching "BRH" inthe line.

The output should be look like:
A] Output:

BRH113	DD	AA	HH	CA	DD DD AA HH 
BRH091	A4	A6	AH	H7	67 HH J8 9J 
BRH0991	AA	D8	C23	V5	H7 BR2 
BRH991 	AA 	HH	GG5	BT0	JJ0

B] Output:

BRH113	BRH091	BRH0991	BRH991
DD	AA	AA	AA
AA	A6	D8	HH
HH	AH	C23	CG5
CA	H7	V5	BTO
DD	67	H7	JJO
DD	HH	BR2
AA	J8
HH	9J

Can we do it with awk, or other unix tool,

Thanks a lot,
Reveri.

A] Output:

awk '{for(i=1;i<=NF;i++) ($i~/^BRH.*/)?$i=RS $i"\t":$i=$i"\t";}1' file
1 Like

A output:

sed 's/ BRH/\
BRH/g' infile

b output:

awk '{for(i=1;i<=NF;i++)
   if ($i ~ "^BRH") {
      key=$i
      keys[++k]=key
      l=1
   } else { m=l>m?l:m;v[key,l++]=$i }
}
END {
    OFS="\t"
    $0=""
    for(j=1;j<=k;j++) $j=keys[j]
    print
    for(i=1;i<=m;i++) {
        $0=""
        for(j=1;j<=k;j++) $j=v[keys[j],i];
        print;
    }
}' infile
1 Like

try also:

awk '$1=$1 {print RS $0}' RS="BRH" OFS="\t" infile

and

awk '{
  for (i=1; i<=NF; i++) {
    if ($i ~ /^BRH/) {c++ ; d=1}
    if (d>m) m=d;
    col[c,d++]=$i "\t";
  }
  for (i=1; i<=m; i++) {
    for (j=1; j<=c; j++) printf col[j,i];
    print "";
  }
}' infile
1 Like

These are great codes, specially like the awk's of all three , bipinajith ,Chubler_XL ,rdrtx1 . Still I am trying to understand . Thanks a lot ...