与split()
中的awk
相反的是什么?
想象一下,我有数组包含字符/整数。
我尝试了什么:
color = "#FFFF00";
printf("color original: %s\n", color);
split(color, chars, "");
joined = "";
for (i=1; i <= length(chars); i++) {
joined = joined + chars[i];
}
printf("color joined: %s\n", joined);
然而输出是:
color original: #FFFF00
color joined: 0
这当然是不正确的。
更新 酷,最后得到以下代码(灵感来自答案中的连接函数):
color = "#FFFF00";
printf("color original: %s\n", color);
split(color, chars, "");
joined = "";
for (i=1; i <= length(chars); i++) {
joined = joined "" chars[i];
}
printf("color joined: %s\n", joined);
诀窍在于加入时不会使用+
符号
答案 0 :(得分:9)
这是一个不依赖于gawk或知道数组长度的解决方案,如果您愿意,可以在每个数组元素之间放置一个分隔符(在本例中为空格)字符串:
color = "#FFFF00"
printf "color original: %s\n", color
split(color, chars, "")
joined = sep = ""
for (i=1; i in chars; i++) {
joined = joined sep chars[i]
sep = " " # populate sep here with whatever string you want between elements
}
printf "color joined: %s\n", joined
我还清理了错误使用printf和虚假的冒号。
答案 1 :(得分:6)
使用GNU awk 4.1
#!/usr/bin/awk -f
@include "join"
BEGIN {
split("#FFFF00", chars, "")
print join(chars, 1, length(chars), SUBSEP)
}
答案 2 :(得分:0)
你想要的(在你的循环中)是string concatenation。
答案 3 :(得分:0)
这是POSIX Awk的一种方式:
br = "red,orange,yellow,green,blue"
ch = split(br, de, ",")
print "original: " br
printf "joined: "
for (ec in de) printf ec == ch ? de[ec] "\n" : de[ec] "-"
输出:
original: red,orange,yellow,green,blue
joined: red-orange-yellow-green-blue
答案 4 :(得分:-1)
知道split()
的反面是join()
,仅谷歌搜索就会向我提供此页面,其中似乎包含解决方案:http://www.gnu.org/software/gawk/manual/html_node/Join-Function.html。它将数组的所有元素连接在一起,并返回相应的字符串。
['f','o','o'] => "foo"
玩得开心