Haohmaru
Haohmaru

Reputation: 578

AWK if inside for loop

I am using a one liner awk to format a file in html

(awk -v var="$tLen" 'BEGIN {OFS="\t"; } { for(i=1;i<=NF;i++) print "<td align=center ROWSPAN=" var ">" $i"</td>"; } END {}' $part1file ) >> "$output"

output:

<td align=center ROWSPAN=4>921</td>
<td align=center ROWSPAN=4>0</td>
<td align=center ROWSPAN=4>29128</td>
<td align=center ROWSPAN=4>0</td>
<td align=center ROWSPAN=4>4f9ea...b6c4a</td>
<td align=center ROWSPAN=4>11/09/2015_13:09:44</td>
<td align=center ROWSPAN=4>1</td>
<td align=center ROWSPAN=4>0</td>
<td align=center ROWSPAN=4>20</td>
<td align=center ROWSPAN=4>4</td>

I need to return this:

<td align=center ROWSPAN=4>921</td>
<td align=center ROWSPAN=4>0</td>
<td align=center ROWSPAN=4>29128</td>
<td align=center ROWSPAN=4>0</td>
<td align=center ROWSPAN=4>4f9ea...b6c4a<br/>11/09/2015_13:09:44</td>
<td align=center ROWSPAN=4>1</td>
<td align=center ROWSPAN=4>0</td>
<td align=center ROWSPAN=4>20</td>
<td align=center ROWSPAN=4>4</td>

Just on the end of the 5th line instead on closing the tag with insert a
then the next row data and then close with

I've tried something like

(awk -v var="$tLen" 'BEGIN {OFS="\t"; } { for(i=1;i<=NF;i++) if (i==6)  print "<br/>"; else print "<td align=center ROWSPAN=" var ">" $i"; if (i==5) print ""; else  print "</td>";  } END {}' $part1file ) >> "$output"

But it doesn't work. I seek help to make this if conditions to work inside the awk any light on this will be much appreciated.

Upvotes: 0

Views: 2763

Answers (2)

karakfa
karakfa

Reputation: 67497

another awk

 awk '{for(i=1;i<=NF;i++) {
          v=$i;
          if(i==5){
             v=$5"<br/>"$6;i++
          } 
          print "<td align=center ROWSPAN=4>" v "</td>"
       }
      }'

print value in given format, which is the field in order, except for 5 where it's a combination of 5 and 6.

I'm not sure why you need the variable var or OFS to be tab.

Upvotes: 1

Functino
Functino

Reputation: 1935

Try adding braces around the body of the for.

awk -v var="$tLen" \
   'BEGIN { OFS = "\t"; }
    {   for (i = 1; i <= NF; i++)
        {
            if (i == 6) print "<br/>"; else print "<td align=center ROWSPAN=" var ">" $i";
            if (i == 5) print ""; else print "</td>";
        }
    }
   ' $part1file >> "$output"

Upvotes: 1

Related Questions