string 使用 awk 循环输入字符串中的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8563745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
loop over characters in input string using awk
提问by jasonmclose
Believe it or not, I can't find the answer to what I would think would be this very basic question.
信不信由你,我找不到这个非常基本的问题的答案。
In awk, how can I loop over the input string character by character? Let's say I just wanted to print them out. Is there an array I can access? Or do I need to use substr?
在 awk 中,如何逐个字符地循环输入字符串?假设我只是想把它们打印出来。有我可以访问的数组吗?或者我需要使用 substr 吗?
Basically, something like:
基本上,类似于:
echo "here is a string" | awk '
{ for(i=0; i<[length of input string]; i++)
printf [value at index i in array x];
}'
Frankly, I'm embarrassed.
老实说,我很尴尬。
回答by Michael J. Barber
You can convert a string to an array using split
:
您可以使用split
以下方法将字符串转换为数组:
echo "here is a string" | awk '
{
split([jaypal:~/Temp] echo "here is a string" | awk -v FS="" '
{for (i=1;i<=NF;i++) printf "Character "i": " $i"\n"}'
Character 1: h
Character 2: e
Character 3: r
Character 4: e
Character 5:
Character 6: i
Character 7: s
Character 8:
Character 9: a
Character 10:
Character 11: s
Character 12: t
Character 13: r
Character 14: i
Character 15: n
Character 16: g
, chars, "")
for (i=1; i <= length(echo here is a string | awk '{
for (i=0; ++i <= length(awk 'kent$ echo "I am a String"|awk '##代码##=gensub(/(.)/,"\1\n","g")'
I
a
m
a
S
t
r
i
n
g
=gensub(/(.)/,"\1\n","g")' file
);)
printf "%s\n", substr(##代码##, i, 1)
}'
); i++) {
printf("%s\n", chars[i])
}
}'
This prints the characters vertically, one per line.
这将垂直打印字符,每行一个。
回答by jaypal singh
By default in awk
the Field Separator (FS)
is space
or tabs
. Since you mentioned you wanted to loop over each character and not word, we will have to redefine the FS to nothing. Something like this -
默认情况下,在awk
该Field Separator (FS)
ISspace
或tabs
。由于您提到要遍历每个字符而不是单词,因此我们必须将 FS 重新定义为空。像这样的东西——
回答by Dimitre Radoulov
Not all awk implementations support the above solutions. In that case you could use substr:
并非所有 awk 实现都支持上述解决方案。在这种情况下,您可以使用substr:
##代码##P.S. In some awkimplementations length without arguments defaults to $0, i.e. lengthand length($0)are equivalent.
PS 在一些awk实现中,没有参数的 length 默认为$0,即length和length($0)是等价的。
回答by Kent
if you have gawk:
如果你有目瞪口呆:
##代码##test:
测试:
##代码##