Shell脚本中遍历字符串的字符

Shell脚本中遍历字符串的字符

本文介绍了如何在POSIX Shell脚本中遍历字符串的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

符合POSIX的外壳程序应提供类似的机制来迭代字符串的集合:

A POSIX compliant shell shall provide mechanisms like this to iterate over collections of strings:

for x in $(seq 1 5); do
    echo $x
done

但是,我如何遍历单词的每个字符?

But, how do I iterate over each character of a word?

推荐答案

有点circuit回,但是我认为这可以在任何符合posix的外壳中使用.我已经在dash中进行了尝试,但是没有方便进行测试的busybox.

It's a little circuitous, but I think this'll work in any posix-compliant shell. I've tried it in dash, but I don't have busybox handy to test with.

var='ab * cd'

tmp="$var"    # The loop will consume the variable, so make a temp copy first
while [ -n "$tmp" ]; do
    rest="${tmp#?}"    # All but the first character of the string
    first="${tmp%"$rest"}"    # Remove $rest, and you're left with the first character
    echo "$first"
    tmp="$rest"
done

输出:

a
b

*

c
d

请注意,不需要在作业右侧加上双引号;我只是喜欢在所有扩展中都使用双引号,而不是试图跟踪将其保留在哪里是安全的.另一方面,绝对必须使用[ -n "$tmp" ]中的双引号,如果字符串包含"*",则需要使用first="${tmp%"$rest"}"中的内部双引号.

Note that the double-quotes around the right-hand side of assignments are not needed; I just prefer to use double-quotes around all expansions rather than trying to keep track of where it's safe to leave them off. On the other hand, the double-quotes in [ -n "$tmp" ] are absolutely necessary, and the inner double-quotes in first="${tmp%"$rest"}" are needed if the string contains "*".

这篇关于如何在POSIX Shell脚本中遍历字符串的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:51