我正在嘗試拆分一些名稱中包含資料的檔案名,并將其匯出到 HTML 表中的不同列中。示例檔案名如下:
10.129.18.225,9998,builtin-v10.conf
目錄中有多個檔案具有相同的格式(IP 地址、埠號、builtin-v(5,7,9 或 10),我也需要對其執行此操作。新檔案不斷添加和洗掉。
我的目標是能夠使用 ' ,
' 作為分隔符/分隔符來拆分檔案名,并將檔案名的不同變數匯入到 HTML 表中,如下所示:
收集器 IP 地址 | 收集器埠 | 網流版 |
---|---|---|
10.129.18.225 | 9998 | 內置-v10 |
10.0.0.0 | 9000 | 內置-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)
任何建議或示例將不勝感激!
uj5u.com熱心網友回復:
另一種方法是=~
在 bash 中使用運算子。
#!/usr/bin/env bash
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 '%s\n%s\n%s\n' "$ip" "$port" "$version"
done
將檔案名的不同變數匯入 HTML 表
可能是這樣的。
#!/usr/bin/env bash
head='<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</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\n' "$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>\n <td>%s</td>\n <td>%s</td>\n <td>%s</td>\n </tr>\n' "$ip" "$port" "$version"
done
printf '%s\n' "$tail"
現在您可以將腳本指向一個檔案,例如
my_script > output.html
uj5u.com熱心網友回復:
您可以通過為其分配 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/517586.html
標籤:重击
下一篇:使用bash腳本檢查多個檔案