我在一個檔案中有一堆針對不同設備的資料,它的設定如下:
device: thing1
data1 data2 data3 data4
data1 data2 data3 data4
...
device: thing2
data1 data2 data3 data4
data1 data2 data3 data4
...
我需要像這樣格式化它:
thing1 data1 data2 data3 data4
thing1 data1 data2 data3 data4
...
thing2 data1 data2 data3 data4
thing2 data1 data2 data3 data4
我在想 awk 是要走的路。標簽“device:”每隔幾百行左右出現一次,表示來自另一個設備的資料集。所以,我可以匹配它并將第二個欄位放入一個變數中。問題是我不確定如何在不排除所有資料行的情況下匹配它。這是我到目前為止所得到的:
-bash-4.2$ awk '/device:/{device=$2; print device, $0;}' data_sets.txt | head -n 10
thing2 device: thing2
thing3 device: thing3
thing6 device: thing6
thing7 device: thing7
another_thing0 device: another_thing0
another_thing1 device: another_thing1
thing2 device: thing2
thing3 device: thing3
thing6 device: thing6
thing7 device: thing7
uj5u.com熱心網友回復:
假設:
device:行僅包含 2 個空格分隔的字串(例如,設備名稱不包含空格)- 不要列印
device:行 - 如果有空行則跳過它們
OFS單個空格的默認輸出欄位分隔符 ( ) 足以生成結果輸出
一個awk想法:
awk '
/^device:/ { device=$2; next } # make note of our new device name; skip to next line of input
NF > 1 { print device,$0 } # if line is not blank/empty then print the label and the current line of input
' data_file.txt
這會產生:
thing1 data1 data2 data3 data4
thing1 data1 data2 data3 data4
thing2 data1 data2 data3 data4
thing2 data1 data2 data3 data4
uj5u.com熱心網友回復:
sed -e "s/^\(.*\)/constant_fieldname \1/" filename
你可以嘗試這樣的事情,在每一行的開頭添加一些東西
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535673.html
標籤:壳unixawksed
