Kalin Borisov
Kalin Borisov

Reputation: 1120

Grep file and export vars in loop

Want to grep file and export the row like separated vars and the last two to be in one var. After that to create loop and export the vars in html tags.

File view:

1.1.1.1 host red  70%     /
1.1.1.1 host green        0%      /dev/shm
1.1.1.1 host green        63%     /staging/om_campaign_files
1.1.1.1 host red  71%     /mnt/OBCDir

Expected view after export the vars:

<tr><td>1.1.1.1<td/><td>host<td/><td color=red>/mnt/OBCDir<td/></tr>

Upvotes: 1

Views: 150

Answers (4)

TrueY
TrueY

Reputation: 7610

A pure bash solution. I assume the output is generated by some external utility. This external utility is simulated by cat infile (see coproc). There is no extra fork except calling the external utility.

coproc cat infile
while read -u ${COPROC[0]} i j k l m; do
  echo "<tr><td>$i<td/><td>$j<td/><td color=$k>$m</td></tr>"
done

This program start a proc in the background. Its stdout is redirected to the file handle stored in ${COPROC[0]}. This handle read in the while-loop.

Or without coproc (mind the space between < and <(!):

while read i j k l m; do
  echo "<tr><td>$i<td/><td>$j<td/><td color=$k>$m</td></tr>"
done < <(cat infile)

If the input is in a file then it can be used like

while read i j k l m; do
  echo "<tr><td>$i<td/><td>$j<td/><td color=$k>$m</td></tr>"
done <infile

Upvotes: 1

Dave Sherohman
Dave Sherohman

Reputation: 46205

If you're looking for something usable in a program, rather than a one-liner at the command prompt:

#!/usr/bin/env perl    

use strict;
use warnings;
use 5.010;

while (my $line = <DATA>) {
  chomp $line;
  my ($ip, $hostname, $color, undef, $mount) = split ' ', $line;
  say "<tr><td>$ip</td><td>$hostname</td><td color=$color>$mount</td></tr>";
}

__DATA__
1.1.1.1 host red  70%     /
1.1.1.1 host green        0%      /dev/shm
1.1.1.1 host green        63%     /staging/om_campaign_files
1.1.1.1 host red  71%     /mnt/OBCDir

Output:

<tr><td>1.1.1.1</td><td>host</td><td color=red>/</td></tr>
<tr><td>1.1.1.1</td><td>host</td><td color=green>/dev/shm</td></tr>
<tr><td>1.1.1.1</td><td>host</td><td color=green>/staging/om_campaign_files</td></tr>
<tr><td>1.1.1.1</td><td>host</td><td color=red>/mnt/OBCDir</td></tr>

Upvotes: 3

Chris Seymour
Chris Seymour

Reputation: 85875

Using awk just insert each field as needed:

awk '{print "<tr><td>"$1"</td><td>"$2"</td><td color="$3">"$5"</td></tr>"}' file
<tr><td>1.1.1.1</td><td>host</td><td color=red>/</td></tr>
<tr><td>1.1.1.1</td><td>host</td><td color=green>/dev/shm</td></tr>
...

Note: also fixed some of the closing tags i.e. <td/> to </td>.

Upvotes: 1

mpapec
mpapec

Reputation: 50667

perl -anE 'say "<tr><td>$F[0]<td/><td>$F[1]<td/><td color=$F[2]>$F[4]<td/></tr>"' file

Upvotes: 1

Related Questions