2012-01-20 40 views
0

我已经试过洞这个我自己,但我非常失败,但是这基本上就是我想在SH(#!/ bin/sh的!)来实现:检查字符串的大小,并根据大小,操纵它?

须藤代码

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为我工作。

感谢

+0

你真的用“上海”(Bourne Shell中,一个老线厂商的Unix平台上)?或者你想用bash或ksh或者?祝你好运。 – shellter

回答

4

有它在伯恩工作,你可以使用:

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

+1,但由于“expr substr foo 1 5”会打印“foo”,所以您可以跳过长度检查并执行SOMEVAR = $(expr substr“$ SOMEVAR”1 5)HIS –

1

你可能使用一个版本伯恩可以在一行中做到这一点,而不调用像expr任何其他命令:

SOMEVAR=${SOMEVAR:0:5}HIS 

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

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