试图从 bash 错误中的字符串中检索前5个字符?

我试图从一个字符串中检索前5个字符,但一直得到一个字符串操作行的 Bad substitution错误,在我的 teststring.sh脚本中有以下行:

TESTSTRINGONE="MOTEST"


NEWTESTSTRING=${TESTSTRINGONE:0:5}
echo ${NEWTESTSTRING}

我已经检查了很多次语法,但是看不出我做错了什么

谢谢

154518 次浏览

Works here:

$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=${TESTSTRINGONE:0:5}
$ echo ${NEWTESTSTRING}
MOTES

What shell are you using?

Depending on your shell, you may be able to use the following syntax:

expr substr $string $position $length

So for your example:

TESTSTRINGONE="MOTEST"
echo `expr substr ${TESTSTRINGONE} 0 5`

Alternatively,

echo 'MOTEST' | cut -c1-5

or

echo 'MOTEST' | awk '{print substr($0,0,5)}'

You can try sed if you like -

[jaypal:~/Temp] TESTSTRINGONE="MOTEST"
[jaypal:~/Temp] sed 's/\(.\{5\}\).*/\1/' <<< "$TESTSTRINGONE"
MOTES

This might work for you:

 printf "%.5s" $TESTSTRINGONE

That parameter expansion should work (what version of bash do you have?)

Here's another approach:

read -n 5 NEWTESTSTRING <<< "$TESTSTRINGONE"

Substrings with ${variablename:0:5} are a bash feature, not available in basic shells. Are you sure you're running this under bash? Check the shebang line (at the beginning of the script), and make sure it's #!/bin/bash, not #!/bin/sh. And make sure you don't run it with the sh command (i.e. sh scriptname), since that overrides the shebang.

echo $TESTSTRINGONE|awk '{print substr($0,0,5)}'

echo 'mystring' |cut -c1-5 is an alternative solution to ur problem.

more on unix cut program

The original syntax will work with BASH but not with DASH. On debian systems you might think you are using bash, but maybe dash instead. If /bin/dash/exist then try temporarily renaming dash to something like no.dash, and then create soft a link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.

Works in most shells

TESTSTRINGONE="MOTEST"
NEWTESTSTRING=${TESTSTRINGONE%"${TESTSTRINGONE#?????}"}
echo ${NEWTESTSTRING}
# MOTES

You were so close! Here is the easiest solution: NEWTESTSTRING=$(echo ${TESTSTRINGONE::5})

So for your example:

$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=$(echo ${TESTSTRINGONE::5})
$ echo $NEWTESTSTRING
MOTES

expr substr $string $position $length

$position starts from 1