将字符串直接拆分为数组
Split a string directly into array
假设我想将一个字符串传递给 awk
,这样一旦我将它拆分(按模式),子字符串就成为关联数组的索引(而不是值)。
像这样:
$ awk -v s="A:B:F:G" 'BEGIN{ # easy, but can these steps be combined?
split(s,temp,":") # temp[1]="A",temp[2]="B"...
for (e in temp) arr[temp[e]] #arr["A"], arr["B"]...
for (e in arr) print e
}'
A
B
F
G
是否有 awkism 或 gawkism 允许将字符串 s
直接拆分为其组件,这些组件成为 arr
中的索引条目?
原因是(大图)我想要这样的东西(伪awk):
awk -v s="1,4,55" 'BEGIN{[arr to arr["1"],arr["5"],arr["55"]} in arr {action}'
可能没用而且复杂得没必要,但我会用 while
、match
和 substr
:
打开游戏
$ awk -v s="A:B:F:G" '
BEGIN {
while(match(s,/[^:]+/)) {
a[substr(s,RSTART,RLENGTH)]
s=substr(s,RSTART+RLENGTH)
}
for(i in a)
print i
}'
A
B
F
G
我很想看到(如果有的话)一些有用的解决方案。我试着玩 asort
s 之类的东西。
不,没有比以下更好的方法将分隔的子字符串映射到数组索引:
split(str,tmp); for (i in tmp) arr[tmp[i]]
FWIW 如果你不喜欢这种方法来完成你最终 pseudo-code 所做的事情:
awk -v s="1,4,55" 'BEGIN{split(s,tmp,/,/); for (i in tmp) arr[tmp[i]]} in arr{action}'
获得相同行为的另一种方法是
awk -v s=",1,4,55," 'index(s,","","){action}'
其他方式awkism
cat file
1 hi
2 hello
3 bonjour
4 hola
5 konichiwa
运行它,
awk 'NR==FNR{d[]; next} in d' RS="," <(echo "1,2,4") RS="\n" file
你明白了,
1 hi
2 hello
4 hola
假设我想将一个字符串传递给 awk
,这样一旦我将它拆分(按模式),子字符串就成为关联数组的索引(而不是值)。
像这样:
$ awk -v s="A:B:F:G" 'BEGIN{ # easy, but can these steps be combined?
split(s,temp,":") # temp[1]="A",temp[2]="B"...
for (e in temp) arr[temp[e]] #arr["A"], arr["B"]...
for (e in arr) print e
}'
A
B
F
G
是否有 awkism 或 gawkism 允许将字符串 s
直接拆分为其组件,这些组件成为 arr
中的索引条目?
原因是(大图)我想要这样的东西(伪awk):
awk -v s="1,4,55" 'BEGIN{[arr to arr["1"],arr["5"],arr["55"]} in arr {action}'
可能没用而且复杂得没必要,但我会用 while
、match
和 substr
:
$ awk -v s="A:B:F:G" '
BEGIN {
while(match(s,/[^:]+/)) {
a[substr(s,RSTART,RLENGTH)]
s=substr(s,RSTART+RLENGTH)
}
for(i in a)
print i
}'
A
B
F
G
我很想看到(如果有的话)一些有用的解决方案。我试着玩 asort
s 之类的东西。
不,没有比以下更好的方法将分隔的子字符串映射到数组索引:
split(str,tmp); for (i in tmp) arr[tmp[i]]
FWIW 如果你不喜欢这种方法来完成你最终 pseudo-code 所做的事情:
awk -v s="1,4,55" 'BEGIN{split(s,tmp,/,/); for (i in tmp) arr[tmp[i]]} in arr{action}'
获得相同行为的另一种方法是
awk -v s=",1,4,55," 'index(s,","","){action}'
其他方式awkism
cat file
1 hi
2 hello
3 bonjour
4 hola
5 konichiwa
运行它,
awk 'NR==FNR{d[]; next} in d' RS="," <(echo "1,2,4") RS="\n" file
你明白了,
1 hi
2 hello
4 hola