我有幾行文字。我想使用 awk 提取特定單詞后的數字。
我嘗試了以下代碼,但它不起作用。
首先,通過以下方式創建測驗檔案:vi test.text. 有 3 列(這 3 個欄位是由其他一些使用 awk 的管道命令生成的)。
Index AllocTres CPUTotal
1 cpu=1,mem=256G 18
2 cpu=2,mem=1024M 16
3 4
4 cpu=12,gres/gpu=3 12
5 8
6 9
7 cpu=13,gres/gpu=4,gres/gpu:ret6000=2 20
8 mem=12G,gres/gpu=3,gres/gpu:1080ti=1 21
請注意,此檔案中有幾個空欄位。我想要實作的是使用如下管道提取gres/gpu=每行中第一個之后的數字(如果gres/gpu=此行中沒有出現,則默認數字為0):cat test.text | awk '{some_commands}'輸出 4 列:
Index AllocTres CPUTotal GPUAllocated
1 cpu=1,mem=256G 18 0
2 cpu=2,mem=1024M 16 0
3 4 0
4 cpu=12,gres/gpu=3 12 3
5 8 0
6 9 0
7 cpu=13,gres/gpu=4,gres/gpu:ret6000=2 20 4
8 mem=12G,gres/gpu=3,gres/gpu:1080ti=1 21 3
uj5u.com熱心網友回復:
首先:awk不需要cat,它可以自己讀取檔案。結合cat和awk通常不鼓勵作為cat 的無用使用。
對于這項任務,我將使用 GNUAWK以下方式,讓file.txt內容為
cpu=1,mem=256G
cpu=2,mem=1024M
cpu=12,gres/gpu=3
cpu=13,gres/gpu=4,gres/gpu:ret6000=2
mem=12G,gres/gpu=3,gres/gpu:1080ti=1
然后
awk 'BEGIN{FS="gres/gpu="}{print $2 0}' file.txt
輸出
0
0
0
3
0
0
4
3
說明:我通知 GNUAWK欄位分隔符 ( FS)gres/gpu=然后對于我列印的每一行第二個欄位增加零。對于沒有gres/gpu= $2空字串的行,當在算術背景關系中使用時,這與零相同,因此零加零等于零。對于至少有 1gres/gpu=加零的行,GNUAWK會找到合法數字的最長前綴,因此3(4th line) 變為3,4,(7th line) 變為4,3,(8th line) 變為3。
(在 GNU Awk 5.0.1 中測驗)
uj5u.com熱心網友回復:
使用您在 GNU 中顯示的示例,awk您可以嘗試以下代碼。用 GNU 撰寫和測驗awk。簡單的解釋是使用awk'smatch函式,其中使用正則運算式gres\/gpu=([0-9] )(在此處轉義/)并創建一個且唯一的捕獲組來捕獲 之后的所有數字=。一旦找到匹配,則在此處列印當前行,然后是陣列的 arr 的第一個元素 0(如果沒有找到任何行的匹配項,則列印零)。
awk '
FNR==1{
print $0,"GPUAllocated"
next
}
{
match($0,/gres\/gpu=([0-9] )/,arr)
print $0,arr[1] 0
}
' Input_file
uj5u.com熱心網友回復:
使用sed
$ sed '1s/$/\tGPUAllocated/;s~.*gres/gpu=\([0-9]\).*~& \t\1~;1!{\~gres/gpu=[0-9]~!s/$/ \t0/}' input_file
Index AllocTres CPUTotal GPUAllocated
1 cpu=1,mem=256G 18 0
2 cpu=2,mem=1024M 16 0
3 4 0
4 cpu=12,gres/gpu=3 12 3
5 8 0
6 9 0
7 cpu=13,gres/gpu=4,gres/gpu:ret6000=2 20 4
8 mem=12G,gres/gpu=3,gres/gpu:1080ti=1 21 3
uj5u.com熱心網友回復:
awk '
BEGIN{FS="\t"}
NR==1{
$(NF 1)="GPUAllocated"
}
NR>1{
$(NF 1)=FS 0
}
/gres\/gpu=/{
split($0, a, "=")
gp=a[3]; gsub(/[ ,].*/, "", gp)
$NF=FS gp
}1' test.text
Index AllocTres CPUTotal GPUAllocated
1 cpu=1,mem=256G 18 0
2 cpu=2,mem=1024M 16 0
3 4 0
4 cpu=12,gres/gpu=3 12 3
5 8 0
6 9 0
7 cpu=13,gres/gpu=4,gres/gpu:ret6000=2 20 4
8 mem=12G,gres/gpu=3,gres/gpu:1080ti=1 21 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/490107.html
下一篇:Heroku無法自動檢測到用于此應用程式的buildpack。嘗試將檔案部署/推送到heroku時出錯-有什么修復嗎?
