![](/img/trans.png)
[英]How to use cut and awk commands to extract text input in a tabular format?
[英]How to use sed/awk commands to cut a string and append to the succeeding lines?
在編寫Shell腳本時需要您的幫助來解決我面臨的一個問題。
在一個文本文件中,我的內容如下:
部署“ 精彩 ”
mon_z1 / 0(c99-2230-333)正在運行
mon_z1 / 1(24a90-00d)正在運行
mon_z1 / 2(4b2-86a5fb2)正在運行
部署“ 彩虹 ”
post_m(333-33-22sd)正在運行
post_s(8-333-33d)正在運行
==================================
我正在尋找類似這樣的輸出-部署名稱應附加到運行狀態:示例:
妙 :正在運行mon_z1 / 0(c99-2230-333)
妙 :mon_z1 / 1(24a90-00d)運行
妙 :正在運行mon_z1 / 2(4b2-86a5fb2)
彩虹 :post_m(333-33-22sd)跑步
彩虹 :post_s(8-333-33d)跑步
請幫助我如何使用sed或awk命令實現
awk解決方案:
awk '/Deployment/{ gsub("\047","",$2); d=$2; next }$3~/running/{ print d,":",$0 }' file
輸出:
wonderful : mon_z1/0 (c99-2230-333) running
wonderful : mon_z1/1 (24a90-00d) running
wonderful : mon_z1/2 (4b2-86a5fb2) running
rainbow : post_m (333-33-22sd) running
rainbow : post_s (8-333-33d) running
/Deployment/{...}
-在遇到Deployment行時執行操作
gsub("\\047","",$2)
-從部署名稱中刪除單引號
d=$2
捕獲部署名稱
$3~/running/
-在遇到具有運行狀態的行時-打印具有相關部署名稱的行
這是另一個awk解決方案:
awk 'BEGIN{FS="\047"}/^Deployment/{ x = $2; next }$0 != ""{ print x, ":" ,$0 }' file
輸出:
wonderful : mon_z1/0 (c99-2230-333) running
wonderful : mon_z1/1 (24a90-00d) running
wonderful : mon_z1/2 (4b2-86a5fb2) running
rainbow : post_m (333-33-22sd) running
rainbow : post_s (8-333-33d) running
它與RomanPerekhrest的類似。 區別在於我使用以下方法過濾出空字符串:
$0 != ""
這要注意,該操作僅在不為空的行上執行。
您要求使用sed或awk,但我將在perl中提供一個易於轉換為awk的示例。 訣竅是您如何訪問匹配項(部署的名稱)。 您可以使用RomanPerekhrest之類的技術並從第二個字段中刪除'標記,也可以使用正則表達式匹配並從匹配組中獲取部署名稱。 這就是我所做的,因為在Perl中它非常簡單。 作為命令行:
cat data | perl -e "use warnings; use strict; my \$deployment; while (<>) { if (\$_ =~ /^Deployment '(.*)'/) { \$deployment = \$1; } else { print(\"\$deployment: \$_\n\"); } }"
或者,為了清楚起見,將其重寫:
use warnings;
use strict;
my $deployment;
while (<>) {
if ($_ =~ /^Deployment '(.*)'/) {
$deployment = $1;
} else {
print("$deployment: $_\n");
}
}
但是請注意,當您用awk重寫此代碼時,不需要while
循環。 Awk的主要優勢在於,它隱式循環遍歷每行並將其拆分為多個字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.