使用 awk 循环输入字符串中的字符 [英] loop over characters in input string using awk

查看:34
本文介绍了使用 awk 循环输入字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

信不信由你,我找不到这个非常基本的问题的答案.

Believe it or not, I can't find the answer to what I would think would be this very basic question.

在 awk 中,如何逐个字符地循环输入字符串?假设我只是想把它们打印出来.有我可以访问的数组吗?或者我需要使用 substr 吗?

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?

基本上,类似于:

echo "here is a string" | awk '
{ for(i=0; i<[length of input string]; i++) 
    printf [value at index i in array x]; 
}'

坦率地说,我很尴尬.

推荐答案

您可以使用 split 将字符串转换为数组:

You can convert a string to an array using split:

echo "here is a string" | awk '
{ 
  split($0, chars, "")
  for (i=1; i <= length($0); i++) {
    printf("%s
", chars[i])
  }
}'

这会垂直打印字符,每行一个.

This prints the characters vertically, one per line.

这篇关于使用 awk 循环输入字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆