简体   繁体   中英

bash shell script that takes two columns of data from text file and uses a for loop with two variables

I am trying to take a text file with two columns of data and loop over each line applying html table tags to each column and write to another file eg

example.txt

1 pool1
2 pool2
3 pool3

This is what I have so far.

for line in $(cat example.txt); do
    count=$(echo $line | awk -F " " '{print$1}')
    pool=$(echo $line | awk -F " " '{print$2}')
    printf "\t<tr>\n\t <td>%s</td> <td>%s</td>\n\t</tr>\n" $count $pool >> example_info.html
done

Current output:

    <tr>
     <td>1</td>
     <td></td>
    </tr>
    <tr>
     <td>pool1</td>
     <td></td>
    </tr>
    <tr>
     <td>2</td>
     <td></td>
    </tr>
    <tr>
     <td>poo2</td>
     <td></td>
    </tr>
    <tr>
     <td>3</td>
     <td></td>
    </tr>
    <tr>
     <td>poo3</td>
     <td></td>
    </tr>

Desired output:

    <tr>
     <td> 1 </td>
     <td> pool1 </td>
    </tr>
    <tr>
     <td> 2 </td>
     <td> pool2 </td>
    </tr>
    <tr>
     <td> 3 </td>
     <td> pool3 </td>
    </tr>

Can anyone point out where my for loop is messed up?

You need a while read loop:

while read count pool
do
    printf "\t<tr>\n\t<td>%s</td><td>%s</td>\n\t</tr>\n" $count $pool >> example_info.html
done < example.txt

You should read up on the Bash read command and decide whether you need the -r option or not.

I assume there is other code to print the HTML heading and body and table heading and ending tags, etc.

This is more suited to awk:

awk '{print "<tr>"; for (i=1; i<=NF; i++) print "\t<td> " $i " </td>"; print "</tr>"}' file
<tr>
    <td> 1 </td>
    <td> pool1 </td>
</tr>
<tr>
    <td> 2 </td>
    <td> pool2 </td>
</tr>
<tr>
    <td> 3 </td>
    <td> pool3 </td>
</tr>

Try this method also

sed 's/\(.*\) \(.*\)/<tr>\n <td> \1 <\/td>\n <td> \2 <\/td>\n<\/tr>/' FileName

Output:

<tr>
 <td> 1 </td>
 <td> pool1 </td>
</tr>
<tr>
 <td> 2 </td>
 <td> pool2 </td>
</tr>
<tr>
 <td> 3 </td>
 <td> pool3 </td>
</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM