我有一個名為 data.txt 的檔案。當我閱讀檔案時,內容如下所示。
$ cat data.txt
name: linuxVol
id: 6
type: Linux
dir excludes: .snapshot*
~snapshot*
.zfs
.isilon
.ifsvar
.lustre
inode: 915720
free_space: 35.6TiB (auto)
total_capacity: 95.0TiB (auto)
number_of_files: 5,789,643
number_of_dirs: 520,710
mounts: https://server1.example.com:30002: /mnt/tube
如何Linux從第三行和server1.example.com最后一行中提取關鍵字,然后在同一行中表示它們,用空格分隔?輸出應顯示如下
Linux server1.example.com
我試圖做這樣的事情,但不知道如何提取server1.example.com
cat data.txt | egrep "type|mounts" | awk '{print $NF}' | tr "\n" " "
輸出是:
Linux /mnt/tube
我的預期輸出:
Linux server1.example.com
用 AWK/SED 解決它對我有用。
謝謝!
uj5u.com熱心網友回復:
每當您的輸入中有標簽值對時,我發現最好創建一個陣列(f[]如下)來保存這些映射,然后您可以通過使用標簽索引該陣列來訪問這些值:
$ cat tst.awk
{
tag = val = $0
sub(/:.*/,"",tag)
sub(/[^:] : */,"",val)
f[tag] = val
}
END {
sub("[^:] ://","",f["mounts"])
sub(/:.*/,"",f["mounts"])
print f["type"], f["mounts"]
}
$ awk -f tst.awk data.txt
Linux server1.example.com
如果您還想處理dir excludes標簽的多行值,則上述內容需要稍作調整,但正如所寫,它使您能夠通過標簽讀取/測驗/列印所有其他值。
uj5u.com熱心網友回復:
如果檔案中只有兩行,一行 with type:,另一行 withmount:并且它們以固定的順序出現,您可以使用
awk '/type:|mounts:/{gsub(/https?:\/\/|:.*/, "", $2); a = (length(a)==0 ? "" : a " ") $2} END{print a}' file
如果一行包含type:or mounts:,則從欄位 2 中洗掉http://orhttps://和之后的所有文本:,然后將該值分配給a或附加一個空格a,并且一旦有檔案結尾,a就會列印該值。
詳情:
/type:|mounts:/- 查找包含type:或的行mounts:gsub(/https?:\/\/|:.*/, "", $2)- 從欄位 2 值中洗掉http://、https://或:和其余字串a = (length(a)==0 ? "" : a " ") $2-assignaspace Field 2 value toaifa不為空,如果是,就給 Field 2 賦值aEND{print a}- 在檔案處理結束時,列印a值。
查看在線演示:
#!/bin/bash
s='name: linuxVol
id: 6
type: Linux
dir excludes: .snapshot*
~snapshot*
.zfs
.isilon
.ifsvar
.lustre
inode: 915720
free_space: 35.6TiB (auto)
total_capacity: 95.0TiB (auto)
number_of_files: 5,789,643
number_of_dirs: 520,710
mounts: h''ttps://server1.example.com:30002: /mnt/tube'
awk '/type:|mounts:/{gsub(/https?:\/\/|:.*/, "", $2); a = (length(a)==0 ? "" : a " ") $2} END{print a}' <<< "$s"
輸出:
Linux server1.example.com
uj5u.com熱心網友回復:
使用gnu-awk您還可以將欄位分隔符設定為:后跟 1 個或多個空格。
然后檢查型別或掛載的第一個欄位,對于掛載,使用捕獲組獲取 https:// 部分之后的部分
鑒于行的順序相同,并且兩個關鍵字都存在,您可以連接這些值。
awk -F ":[[:space:]] " '
$1 == "type" {s = $2}
$1 == "mounts" && match($2, /https?:\/\/([^[:space:]:] )/, a) {s = s " " a[1]}
END {print s}
' data.txt
輸出
Linux server1.example.com
uj5u.com熱心網友回復:
我認為sed還需要一個解決方案
$ sed -n '/type:/{s/[^ ]* \(.*\)/\1/;h;d};/mounts:/{s|[^/]*//\([^:]*\).*|\1|;x;G;s/\n/ /p}' input_file
Linux server1.example.com
或者作為腳本
$ cat script.sed
/type:/ {
s/[^ ]* \(.*\)/\1/
h
d
}
/mounts:/ {
s|[^/]*//\([^:]*\).*|\1|
x
G
s/\n/ /p
}
$ sed -nf script.sed input_file
Linux server1.example.com
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474217.html
上一篇:XCodeAdmob構建失敗問題
