WholeWord="Foo bar sells drinks"
for (( character=0; character<${#WholeWord}; character++ )); do
echo ${WholeWord:$character}
done
打印出来:
Foo bar sells drinks
oo bar sells drinks
o bar sells drinks
bar sells drinks
bar sells drinks
ar sells drinks
r sells drinks
sells drinks
sells drinks
ells drinks
lls drinks
ls drinks
s drinks
drinks
drinks
rinks
inks
nks
ks
s
我不想修剪每个第一个字母的第一个字母,而是想修剪最后一个字母,创建输出如下:
Foo bar sells drinks
Foo bar sells drink
Foo bar sells drin
Foo bar sells dri
etc.
答案 0 :(得分:3)
像这样使用负长度作为第二个参数:
echo "$WholeWord"
for (( character=1; character<${#WholeWord}; character++ )); do
echo "${WholeWord:0: -$character}"
done
Foo bar sells drinks
Foo bar sells drink
Foo bar sells drin
Foo bar sells dri
Foo bar sells dr
Foo bar sells d
Foo bar sells
Foo bar sells
Foo bar sell
Foo bar sel
Foo bar se
Foo bar s
Foo bar
Foo bar
Foo ba
Foo b
Foo
Foo
Fo
F
答案 1 :(得分:3)
几乎所有shell都使用此脚本 每次打印后,只需将字符串中的一个字符串切掉:
-f
或者,如果你必须使用#!/bin/sh
WholeWord="Foo bar sells drinks"
foo="$WholeWord"
while [ "$foo" ]; do
printf '%s\n' "$foo"
foo="${foo%?}"
done
,那么每一步的长度都会降到1:
Substring Expansion
WholeWord="Foo bar sells drinks"
for (( character=${#WholeWord}; character>0; character-- )); do
printf '%s\n' "${WholeWord:0:$character}"
done
答案 2 :(得分:2)
#!/bin/bash
WholeWord="Foo bar sells drinks"
for (( character=${#WholeWord}; character>0; --character )); do
echo ${WholeWord:0:$character}
done
此代码的作用:
从整个字符串的大小向后计数到0,从字符串的开头给出该字符数。
答案 3 :(得分:1)
不计算字符
$ foo="Foo bar sells drinks"
$ while [[ ! -z $foo ]]; do echo $foo; foo=$(sed 's/.$//' <<< $foo); done
Foo bar sells drinks
Foo bar sells drink
Foo bar sells drin
Foo bar sells dri
Foo bar sells dr
Foo bar sells d
Foo bar sells
Foo bar sell
Foo bar sel
Foo bar se
Foo bar s
Foo bar
Foo ba
Foo b
Foo
Fo
F