Shell 检查字符串的大小,并根据大小对其进行操作?

Shell 检查字符串的大小,并根据大小对其进行操作?,shell,sh,Shell,Sh,我自己也尝试过,但失败惨重,但这基本上就是我在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 "

我自己也尝试过,但失败惨重,但这基本上就是我在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对我有效


感谢您在伯恩使用它,您可以使用:

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

要使其在伯恩正常工作,您可以使用:

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

您可能正在使用一个版本的Bourne,它可以在一行中完成此操作,而无需调用任何其他命令,如
expr

SOMEVAR=${SOMEVAR:0:5}HIS
但是如果您的shell不支持这种奇特的子字符串提取语法,您可以使用sed。(请注意,并非所有版本的
expr
都支持substr。)


您可能正在使用一个版本的Bourne,它可以在一行中完成此操作,而无需调用任何其他命令,如
expr

SOMEVAR=${SOMEVAR:0:5}HIS
但是如果您的shell不支持这种奇特的子字符串提取语法,您可以使用sed。(请注意,并非所有版本的
expr
都支持substr。)

您是否真的在使用“sh”(Bourne Shell,在旧的Unix供应商平台上)?或者你想用bash或者ksh或者???祝你好运。你真的在使用“sh”(Bourne Shell,在旧的Unix厂商平台上)吗?或者你想用bash或者ksh或者???祝你好运。+1,但由于“expr substr foo 15”打印“foo”,你可以跳过长度检查,只需执行SOMEVAR=$(expr substr“$SOMEVAR”15)HIS+1,但由于“expr substr foo 15”打印“foo”,你可以跳过长度检查,只需执行SOMEVAR=$(expr substr“$SOMEVAR”15)HIS