bash 如何在 Unix Shell 中遍历字符串中的每个字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35263929/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:12:58  来源:igfitidea点击:

How to iterate through each letter in a string in Unix Shell

bashshellunix

提问by oliv

I am trying to iterate through a string taken as an input through the readcommand. I'm trying to output the number of each letter and each letter It should then use a loop to output each letter in turn. For example, if the user enters "picasso", the output should be:

我正在尝试通过读取命令遍历作为输入的字符串。我正在尝试输出每个字母和每个字母的编号,然后应该使用循环依次输出每个字母。例如,如果用户输入“毕加索”,则输出应为:

Letter 1: p Letter 2: i Letter 3: c Letter 4: a Letter 5: s Letter 6: s Letter 7: o

字母 1:p 字母 2:i 字母 3:c 字母 4:a 字母 5:s 字母 6:s 字母 7:o

Here is my current code:

这是我当前的代码:

#!/bin/bash

# Prompt a user to enter a word and output each letter in turn.


read -p "Please enter a word: " word

for i in $word
do
 echo "Letter $i: $word"
done

Should I be placing the input to an array? I'm still new to programming loops but I'm finding it impossible to figure out the logic.

我应该将输入放入数组吗?我对编程循环还是个新手,但我发现无法弄清楚逻辑。

Any advice? Thanks.

有什么建议吗?谢谢。

回答by oliv

Combining answers from dtmilano and patrat would give you:

结合 dtmilano 和 patrat 的答案会给你:

read -p "Please enter a word: " word

for i in $(seq 1 ${#word})
do
 echo "Letter $i: ${word:i-1:1}"
done

${#word} gives you the length of the string.

${#word} 为您提供字符串的长度。

回答by Diego Torres Milano

Use the substring operator

使用子串运算符

 ${word:i:1}

to obtain the i'th character of word.

获得单词的第 i 个字符。

回答by patrat

Check out seq mechanism in bash

查看 bash 中的 seq 机制

For example:

例如:

seq 1 10

Will give you

会给你

1 2 3 4 5 6 7 8 9 10

You can try with letters

你可以试试字母

echo {a..g}

Result

结果

 a b c d e f g

Now you should handle your problem

现在你应该处理你的问题