检查字符串的大小,并根据大小,操纵它?

时间:2012-01-20 14:12:18

标签: shell sh

我已经尝试过这个我自己,但我失败了,但这基本上是我想要实现的目标(#!/ bin / sh):

sudo代码

SOMEVAR="VALUE"

if [ $SOMEVAR.length > 5]
then 
# Take the first 5 characters of the string and add "HIS" to the end of them, assigning this new value to the SOMEVAR variable. 
else
#just add "HIS" to the end of the string
fi

如果有人能告诉我如何实现这一点,我将非常感激,我尝试过使用$ {#SOMEVAR}> 5和$ {SOMEVAR:0:5}但这个dosnet对我有效。

谢谢

2 个答案:

答案 0 :(得分:4)

要让它在Bourne中运行,您可以使用:

#!/bin/sh
SOMEVAR="HELLO WORLD"
if [ ${#SOMEVAR} -gt 5 ]
then
    SOMEVAR=`expr substr "$SOMEVAR" 1 5`    
fi
SOMEVAR="${SOMEVAR}HIS"

答案 1 :(得分:1)

你可能正在使用一个版本的Bourne,它可以在一行中执行此操作,而无需调用expr之类的任何其他命令:

SOMEVAR=${SOMEVAR:0:5}HIS

但是如果你的shell不支持那种花哨的子字符串提取语法,你可以使用sed。 (请注意,并非expr的所有版本都支持substr。)

SOMEVAR=`echo "$SOMEVAR" | sed 's/^\(.....\).*/\1/'`HIS