gpt4 book ai didi

awk - awk 是二维数组还是类似于存储值的东西?

转载 作者:行者123 更新时间:2023-12-04 14:01:57 28 4
gpt4 key购买 nike

大家好,我是 awk 的新手,我可以问一下我有这样的输入文件吗:

# ABC DEFG
value1 GH
value2 GH
value3 GH
# BCF SQW
value4 GH
value5 GH
# BEC YUW
value6 GH
value7 GH

期望输出:

##### ABC DEFG #####
DEFG_ABC
ABC_DEFG
value1 ABC
value1 DFG
value2 ABC
value2 DFG
value3 ABC
value3 DFG
##### BCF SQW #####
BCF_SQW
SQW_BCF
value4 BCF
value4 SQW
value5 BCF
value5 SQF
##### BEC YUW #####
BEC_YUW
YUW_BEC
value6 BEC
value6 YUW
value7 BEC
value7 YUW

我已经将文件 $2 和 $3 分开,将字符 # 放入数组中,如下所示

awk '
/^#/ {
a[na++] = $2
b[nb++] = $3
}
END {
for(i = 0; i < na; i ++){
print ("######" a[i] " " b[i] "#####")
print (a[i] "_" b[i])
print (b[i] "_" a[i])
}
}
' input

但我不知道如何将“#”行之间的所有行的 $1 存储到数组中,有人怎么做吗?非常感谢

最佳答案

使用您展示的示例,请尝试遵循 awk 代码。用 GNU awk 编写和测试应该可以在任何 awk 中使用。

awk '
/^#/{
sub(/^#/,"##### ")
print $0," #####"
val1=$2
val2=$3
print val1"_"val2 ORS val2"_"val1
next
}
{
print $1,val1 ORS $1,val2
}
' Input_file

说明: 为以上添加详细说明。

awk '                          ##Starting awk program from here.
/^#/{ ##Checking condition if line starts from #.
sub(/^#/,"##### ") ##Substituting starting # with #####
print $0," #####" ##Printing current line follows by ##### here.
val1=$2 ##Creating val1 which has 2nd field in it.
val2=$3 ##Creating val2 which has 3rd field in it.
print val1"_"val2 ORS val2"_"val1 ##Printing val1 _ val2 newline val2 _ val1.
next ##next will skip further statements from here.
}
{
print $1,val1 ORS $1,val2 ##Printing 1st field val1 ORS 1st field val2 here.
}
' Input_file ##Mentioning Input_file name here.

关于awk - awk 是二维数组还是类似于存储值的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69717630/

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