Shell变量的截取
1. 变量算术运算
使⽤${#VAR} 语法将计算⼀个变量当中字符的数量
shell 字符串长度[bob in ~] echo $SHELL
/bin/bash
[bob in ~] echo ${#SHELL}
9
[bob in ~] ARRAY=(one two three)
[bob in ~] echo ${#ARRAY}
3
2. 变量的转化
1. 替换
${VAR:-WORD} 如果 VAR 没有定义或者是空值,由WORD的值替换;否则输出 VAR 的值:[bob in ~] echo ${TEST:-test}
test
[bob in ~] echo $TEST
[bob in ~] export TEST=a_string
[bob in ~] echo ${TEST:-test}
a_string
[bob in ~] echo ${TEST2:-$TEST}
a_string
如果 (-) 使⽤等号(=)替换,后者的值会被赋值到前者上:
[bob in ~] echo $TEST2
[bob in ~] echo ${TEST2:=$TEST}
a_string
以下语法测试⼀个变量是否存在。如果没有设置,WORD的扩展打印到标准输出且⾮交互shell退出。[bob in ~]echo ${TEST2:?WORD}
(与${VAR:-WORD}的区别,${VAR:?WORD}是⼀个错误,不是⼀个正常的输出,⽽前者回正常输出和${VAR:=WORD})的区别,${VAR:?WORD}不会把word的值赋给var)
证明:
[bob in ~] cat vartest.sh
#!/bin/bash
# This script tests whether a variable is set. If not,
# it exits printing a message.
echo ${TESTVAR:?"There's so much I still wanted "}
echo "TESTVAR is set, we can proceed."
[bob in testdir] ./vartest.sh
./vartest.sh: line 6: TESTVAR: There's so much I still wanted
[bob in testdir] export TESTVAR=present
[bob in testdir] ./vartest.sh
present
TESTVAR is set, we can proceed.
3.字符串切⽚
要从⼀个变量之中,删除(注意,这⾥是删除⽽不是截取)等于OFFSET数量的字符,使⽤这样的语法:
${VAR:OFFSET:LENGTH}
LENGTH参数定义了在偏移点offset之后第⼀个字符开始需要保留多少字符。如果LENGTH省略,就是⽤剩余的变量的内容。[bob in ~] export STRING="thisisaverylongname"
[bob in ~] echo ${STRING:4}
isaverylongname
[bob in ~] echo ${STRING:6:5}
avery
${VAR#WORD} and ${VAR##WORD}
注:这⾥是这样定义的:ARRAY=(one two one three one four),是数组
⽽这样定义的ARRAY="one two one three one four"是⼀个字符串,数组会对每⼀个元素操作。
[bob in ~] echo ${ARRAY[*]}
one two one three one four
[bob in ~] echo ${ARRAY[*]#one}
two three four
[bob in ~] echo ${ARRAY[*]#t}
one wo one hree one four
[bob in ~] echo ${ARRAY[*]#t*}
one wo one hree one four
表⽰对每个元素,从左开始数,直到匹配到t*的最短的为⽌,截除掉。
[bob in ~] echo ${ARRAY[*]##t*}
one one one four
表⽰对每个元素,从左开始数,直到匹配到t*的最长的为⽌,截除掉。
[bob in ~] echo $STRING
thisisaverylongname
%与#作⽤类似,但是从变量的右边开始匹配
[bob in ~] echo ${STRING%name}
thisisaverylong
4.替换:
${VAR/PATTERN/STRING}
or
${VAR//PATTERN/STRING}
语法。第⼀种形式仅仅替换第⼀个匹配的项⽬,第⼆个⽤STRING替换所有匹配PATTERN的项⽬。
[bob in ~] echo ${STRING/name/string}
thisisaverylongstring

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。