#!/bin/sh read -p "Enter sequence: " seq for char in $seq; do echo "$char" done
我从标准输入中读取字符序列,例如1234(),我想把它改成这样:
1234(),
'1' '2' '3' '4' '(' ')' ','
我不想回显这个序列。我需要它有这个新值。在标准的sh脚本中可以吗?
jv2fixgn1#
这适用于所有可打印的ASCII字符(可能还适用于任何非NUL字节),无需外部程序的帮助(printf通常是内置的):
printf
string="$(printf "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#\$%%&\'()*+,-./:;<=>?@[\\]^_\`{|}~ \t\n\r")" while [ -n "${string}" ]; do character="$(printf '%c.' "${string}")" character="${character%.}" echo "Character: '${character}'" string="${string#?}" done
注意格式字符串中的额外非空格字符,我们需要它,这样命令替换就不会删除可能的LF。
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可能会更快。
sed
7gs2gvoe2#
你可以用sed(1)拆分字符串:
seq=`printf "%s\n" "$seq" | sed 's/./ &/g'`
2条答案
按热度按时间jv2fixgn1#
这适用于所有可打印的ASCII字符(可能还适用于任何非NUL字节),无需外部程序的帮助(
printf
通常是内置的):注意格式字符串中的额外非空格字符,我们需要它,这样命令替换就不会删除可能的
LF
。对于长字符串,
sed
可能会更快。7gs2gvoe2#
你可以用
sed
(1)拆分字符串: