2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
我會(huì)將您的輸入文件轉(zhuǎn)換為 CSV,因?yàn)樗m合原始表格數(shù)據(jù),也因?yàn)?Go 語(yǔ)言在其標(biāo)準(zhǔn)庫(kù)中有一個(gè) CSV 編碼器/解碼器:
awk -v OFS=',' '
$1 == "Num" {
count = $3
type = $2
getline
if ( !header++ ) {
$(NF+1) = "ID"
}
for ( id = 1; id <= count; id++ ) {
getline
$(NF+1) = type id
}
}
' file.txt
警告:代碼不會(huì)對(duì)字段進(jìn)行 CSV 轉(zhuǎn)義
INDEX,LOAD,MODEL_LOAD,INST,MEM,SHARE_MEM,P2P_MEM,DEVICE,NAMESPACE,ID
1,2,3,4,50,600,700,/dev/nvme0,/dev/nvme0n1,decoders:1
1a,2b,3c,4c,5d,6e,7f,/dev/nvme1,/dev/nvme1n1,decoders:2
2a,2b,2c,3,0,0,0,/dev/nvme0,/dev/nvme0n1,encoders:1
1,0,0,0,0,0,0,/dev/nvme1,/dev/nvme1n1,encoders:2
0,0,0,0,0,0,0,/dev/nvme0,/dev/nvme0n1,scalers:1
1,0,0,0,0,0,0,/dev/nvme1,/dev/nvme1n1,scalers:2
NB在 Go 中為您的輸入格式編寫解析器應(yīng)該不會(huì)那么困難

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
如何直接從您關(guān)心的 Go 文本開始?與使用 shell 實(shí)用程序相比,您在 Go 中擁有更多的控制權(quán)。
這是一個(gè)小型狀態(tài)機(jī),用于查找前導(dǎo)文本“Num”以指示新項(xiàng)目的開始。下一行是標(biāo)題,它被跳過(guò),后面的行被轉(zhuǎn)換為一個(gè)行,被添加到那個(gè)項(xiàng)目。在項(xiàng)目之間的邊界和輸入文本/文件的末尾,最后一個(gè)項(xiàng)目被添加到所有項(xiàng)目的集合中。
package main
import (
"bufio"
"fmt"
"regexp"
"strings"
)
var txt = `
Num item1: 2
INDEX LOAD MODEL_LOAD INST MEM SHARE_MEM P2P_MEM DEVICE NAMESPACE
1 2 3 4 50 600 700 1 1
1a 2b 3c 4c 5d 6e 7f 2 2
Num item2: 2
INDEX LOAD MODEL_LOAD INST MEM SHARE_MEM P2P_MEM DEVICE NAMESPACE
2a 2b 2c 3 0 0 0 1 1
1 0 0 0 0 0 0 2 2
Num item3: 1
INDEX LOAD MODEL_LOAD INST MEM SHARE_MEM P2P_MEM DEVICE NAMESPACE
i iib iic iii zero zero zero i i
**************************************************
`
var columns = regexp.MustCompile(`\s+`)
type Row struct {
Index,
Load,
Model_Load,
Inst_Mem,
Share_Mem,
P2p_Mem,
Device,
Namespace string
}
type Item []Row
func main() {
r := strings.NewReader(txt)
scanner := bufio.NewScanner(r)
items := make([]Item, 0)
var item Item
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if len(line) == 0 ||
strings.HasPrefix(line, "***") {
continue
}
// find beginning of an "item": if any previous item, save it and
// reset item to append future rows; skip header line; continue
if strings.HasPrefix(line, "Num item") {
if len(item) > 0 {
items = append(items, item)
item = make(Item, 0)
}
scanner.Scan() // skip header
continue
}
cols := columns.Split(line, -1)
row := Row{cols[0], cols[1], cols[2], cols[3], cols[4], cols[5], cols[6], cols[7]}
item = append(item, row)
}
// deal with last/trailing item
if len(item) > 0 {
items = append(items, item)
}
for i, item := range items {
fmt.Printf("Item %d\n", i+1)
for _, row := range item {
fmt.Println(row)
}
}
}
打印以下內(nèi)容:
Item 1
{1 2 3 4 50 600 700 1}
{1a 2b 3c 4c 5d 6e 7f 2}
Item 2
{2a 2b 2c 3 0 0 0 1}
{1 0 0 0 0 0 0 2}
Item 3
{i iib iic iii zero zero zero i}
我不知道有什么更好的方法來(lái)創(chuàng)建結(jié)構(gòu),但它是直接的,而且相當(dāng)干凈。
- 2 回答
- 0 關(guān)注
- 136 瀏覽
添加回答
舉報(bào)