【问题标题】:Split filenames at delimiter and write to HTML table在分隔符处拆分文件名并写入 HTML 表
【发布时间】:2022-12-25 14:02:09
【问题描述】:

我试图拆分一些名称中包含数据的文件名,并将其导出到 HTML 表中的不同列中。示例文件名如下:

 10.129.18.225,9998,builtin-v10.conf

目录中有多个格式相同的文件(IP 地址、端口号、内置-v(5、7、9 或 10),我也需要对其执行此操作。不断添加和删除新文件。

我的目标是能够使用“,”作为分隔符/分隔符来拆分文件名,并将文件名的不同变量导入到 HTML 表中,如下所示:

Collector IP Address Collector Port Netflow Version
10.129.18.225 9998 builtin-v10
10.0.0.0 9000 builtin-v9

我看过一些看起来相似的不同帖子,但我只是想知道在 bash 中实现此目的的最佳方法?

我目前有以下脚本,但我认为它不正确。

    #!/bin/bash

$file="/usr/local/flowsim/data/*.conf"
data=$(echo $file | cut -d"," -f1 | tr -d ",")

Collector=$(echo $file | cut -d"," -f1) >> "/usr/local/flowsim/active-flows.html"
Port=$(echo $file | cut -d"," -f2 | cut -d"," -f1)

任何建议或例子将不胜感激!

【问题讨论】:

    标签: bash


    【解决方案1】:

    另一种方法是在 bash 中使用 =~ 运算符。

    #!/usr/bin/env bash
    
    head='<!DOCTYPE html>
    <html>
    <style>
    table, th, td {
      border:1px solid black;
      text-align: center;
      vertical-align: middle;
    }
    </style>
    <body>
    <h2>A basic HTML table</h2>
    <table style="width:50%">
      <tr>
        <th>Collector IP Addess</th>
        <th>Collector Port</th>
        <th>Netflow Version</th>
      </tr>'
    
    tail='</table>
    </body>
    </html>'
    
    printf '%s
    ' "$head"
    
    shopt -s nullglob
    
    for file in ./usr/local/flowsim/data/*,*,*.conf; do
      [[ $file =~ ([^/]+),(.+),(.+).conf$ ]] &&
      ip=${BASH_REMATCH[1]}
      port=${BASH_REMATCH[2]}
      version=${BASH_REMATCH[3]}
      printf ' <tr>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
     </tr>
    ' "$ip" "$port" "$version"
    done
    
    printf '%s
    ' "$tail"
    

    现在您可以将脚本指向一个文件,例如

    my_script > output.html
    

    【讨论】:

    • 哦,++ed 得到了一个很好的答案,包括生成一个 html 文件!
    • 谢谢两位!我使用了上面的第二个代码示例,它看起来运行良好。无论如何我可以使用该代码从文件中删除后缀吗?目前,Netflow 版本列中的输入有 .conf,如果可能,我想将其删除,谢谢!
    • @Davearoo32。根据您的要求更新了正则表达式。
    • @Jetchisel 感谢您的协助,工作得很好 :)
    【解决方案2】:

    您可以通过将 bash 变量 IFS 分配给文件名来用逗号分隔文件名。你能试试吗:

    #!/bin/bash
    
    for file in /usr/local/flowsim/data/*.conf; do                  # loop over the *.conf files
        if [[ -f $file ]]; then                                     # make sure $file exist
            f="$(basename "$file" ".conf")"                         # strip directory and suffix from $file
            IFS=, read -r data Collector Port <<< "$f"              # split "$f" on commas and assign variables
            # echo "$data $Collector $Port"                         # just to check the variables
            # add to the html table using the variables             # do your job here
        fi
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2019-03-19
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多