gpt4 book ai didi

linux - 搜索 2 个文件并输出 common 并打印额外的一行 unix 脚本

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:32 24 4
gpt4 key购买 nike

我有这段代码,但它给我一个错误

awk '
FNR == NR {
# reading get_ids_only.txt
values[$1] = ""
next
}
BEGIN {
# reading default.txt
for (elem in values){
if ($0 ~ elem){
if (values[elem] == ""){
values[elem] = "\"" $0 "\""
getline;
values[elem] = "\n"" $0 ""\n"
}
else{
values[elem] = values[elem] ", \"" $0 "\""
getline;
values[elem] = values[elem] "\n"" $0 ""\n"
}
}
}
END {
for (elem in values)
print elem " [" values[elem] "]"
}
' get_ids_only.txt default.txt

错误说

awk: syntax error at source line 23
context is
>>> END <<< {
awk: illegal statement at source line 24
awk: illegal statement at source line 24
missing }

这是我的 END{ } 函数开始的地方...

我要做的是.. 比较文件 1 中的字符串..... 如果在文件 2 中找到该字符串,则打印该字符串并打印其后的行。然后跳过空间。

输入1:

 message id "hello"
message id "good bye"
message id "what is cookin"

输入2:

 message id "hello"
message value "greetings"

message id "good bye"
message value "limiting"

message id "what is there"
message value "looking for me"

message id "what is cooking"
message value "breakfast plate"

输出:

 should print out all the input1, grabbing the message value from input 2.

谁能指导我为什么会出现此错误?

我在我的 mac 上使用终端。

最佳答案

这是你的 BEGIN block ,带有推荐的缩进和注释,你能看出问题所在吗?

BEGIN {
# reading default.txt
for (elem in values){
if ($0 ~ elem){
if (values[elem] == ""){
values[elem] = "\"" $0 "\""
getline;
values[elem] = "\n"" $0 ""\n"
}
else{
values[elem] = values[elem] ", \"" $0 "\""
getline;
values[elem] = values[elem] "\n"" $0 ""\n"
} # End inner if
} # End outer if
} # End for loop

您缺少右括号。请注意,在与 $0 的最终连接中,实际上引用了 $0

这还有其他一些问题,我不确定您要做什么,但这似乎是一种非常不合适的方法。通常,如果您发现自己过度使用 getline,您应该考虑将代码分散到具有适当条件的单独 block 中。参见 this article关于 getline 的滥用。

更笨拙的解决方法

如果我理解正确,这就是我解决这个任务的方式:

extract.awk

FNR==NR  { id[$0]; next }  # Collect id lines in the `id' array
$0 in id { f=1 } # Use the `f' as a printing flag
f # Print when `f' is 1
NF==0 { f=0 } # Stop printing after an empty line

像这样运行它:

awk -f extract.awk input1 input2

输出:

message id "hello"
message value "greetings"

message id "good bye"
message value "limiting"

关于linux - 搜索 2 个文件并输出 common 并打印额外的一行 unix 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15355133/

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