gpt4 book ai didi

if-statement - 如何根据条件使连续行进入列?

转载 作者:行者123 更新时间:2023-12-03 23:41:49 24 4
gpt4 key购买 nike

任何人都可以帮助获得如下所述的所需输出吗?

❯ cat example.txt
hostname a-b-c
services Apache
hostname d-e-f
services Python
hostname g-h-i
vmhostname u-v-w
vmhostname x-y-z
我想得到如下输出
a-b-c Apache
d-e-f Python
g-h-i No services
u-v-w No services
x-y-z No services
我使用过 awk 但得到不同的输出。
❯ cat example.txt | awk 'NR%2{printf $0" ";next;}1'
hostname a-b-c services Apache
hostname d-e-f services Python
hostname g-h-i vmhostname u-v-w
vmhostname x-y-z %

最佳答案

您能否尝试在 GNU awk 中使用所示示例进行以下、编写和测试? .

awk '
/hostname/{
if(val){
print val,"NO service"
}
val=$2
next
}
/services/{
print val,$2
val=""
}
END{
if(val){
print val,"NO service"
}
}' Input_file
说明:为上述添加详细说明。
awk '                         ##Starting awk program from here.
/hostname/{ ##checking condition if line has hostname here.
if(val){ ##checking condition if val is NOT NULL here.
print val,"NO service" ##printing val and string NO service here.
}
val=$2 ##setting val to 2nd field here.
next ##next will skip all statements from here.
}
/services/{ ##Checking condition if line has services in it then do following.
print val,$2 ##Printing val and 2nd field here.
val="" ##Nullifying val here.
}
END{ ##starting END block of this program from here.
if(val){ ##checking condition if val is NOT NULL here.
print val,"NO service" ##printing val and string NO service here.
}
}' Input_file ##Mentioning Input_file name here.
输出如下。
a-b-c Apache
d-e-f Python
g-h-i NO service
u-v-w NO service
x-y-z NO service

关于if-statement - 如何根据条件使连续行进入列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65302259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com