shell 在POSIX sh中迭代字符串中的字符

qojgxg4l  于 2023-04-21  发布在  Shell
关注(0)|答案(2)|浏览(126)
#!/bin/sh

read -p "Enter sequence:  " seq

for char in $seq; do
    echo "$char"
done

我从标准输入中读取字符序列,例如1234(),
我想把它改成这样:

'1' '2' '3' '4' '(' ')' ','

我不想回显这个序列。我需要它有这个新值。
在标准的sh脚本中可以吗?

jv2fixgn

jv2fixgn1#

这适用于所有可打印的ASCII字符(可能还适用于任何非NUL字节),无需外部程序的帮助(printf通常是内置的):

string="$(printf "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#\$%%&\'()*+,-./:;<=>?@[\\]^_\`{|}~ \t\n\r")"
while [ -n "${string}" ]; do
    character="$(printf '%c.' "${string}")"
    character="${character%.}"
    echo "Character: '${character}'"
    string="${string#?}"
done

注意格式字符串中的额外非空格字符,我们需要它,这样命令替换就不会删除可能的LF

Character: '0'
Character: '1'
Character: '2'
Character: '3'
Character: '4'
Character: '5'
Character: '6'
Character: '7'
Character: '8'
Character: '9'
Character: 'a'
Character: 'b'
Character: 'c'
Character: 'd'
Character: 'e'
Character: 'f'
Character: 'g'
Character: 'h'
Character: 'i'
Character: 'j'
Character: 'k'
Character: 'l'
Character: 'm'
Character: 'n'
Character: 'o'
Character: 'p'
Character: 'q'
Character: 'r'
Character: 's'
Character: 't'
Character: 'u'
Character: 'v'
Character: 'w'
Character: 'x'
Character: 'y'
Character: 'z'
Character: 'A'
Character: 'B'
Character: 'C'
Character: 'D'
Character: 'E'
Character: 'F'
Character: 'G'
Character: 'H'
Character: 'I'
Character: 'J'
Character: 'K'
Character: 'L'
Character: 'M'
Character: 'N'
Character: 'O'
Character: 'P'
Character: 'Q'
Character: 'R'
Character: 'S'
Character: 'T'
Character: 'U'
Character: 'V'
Character: 'W'
Character: 'X'
Character: 'Y'
Character: 'Z'
Character: '!'
Character: '"'
Character: '#'
Character: '$'
Character: '%'
Character: '&'
Character: '''
Character: '('
Character: ')'
Character: '*'
Character: '+'
Character: ','
Character: '-'
Character: '.'
Character: '/'
Character: ':'
Character: ';'
Character: '<'
Character: '='
Character: '>'
Character: '?'
Character: '@'
Character: '['
Character: '\'
Character: ']'
Character: '^'
Character: '_'
Character: '`'
Character: '{'
Character: '|'
Character: '}'
Character: '~'
Character: ' '
Character: '    '
Character: '
'
'haracter: '

对于长字符串,sed可能会更快。

7gs2gvoe

7gs2gvoe2#

你可以用sed(1)拆分字符串:

seq=`printf "%s\n" "$seq" | sed 's/./ &/g'`

相关问题