前言
shell中,对变量的输出是最为常见,根据所遇到的情况,对变量的操作进行下总结。
一、变量特殊字符的输出
变量中,有时我们会输出特殊字符,转义字符等,此时直接echo输出则会直接输出,而不会有所想要的结果,因此需要添加-e 属性。实例如下:
#!/bin/bash
test=100
echo "your score is $test \n"
echo "========"
echo -e "your score is $test \n"
执行结果如下:
如图所示,直接输入则会将转义字符输出,但是加上-e则可以输出想要结果。
再如若转换下shell的定义,将/bin/bash改变为/bin/sh,大家可以看下结果,实例如下:
#!/bin/sh
test=100
echo "your score is $test \n"
echo "========"
echo -e "your score is $test \n"
执行结果如下:
更改声明,会发现,在/bin/sh的模式下,-e的命令则没有了,他可以自动识别输出结果的转义字符。这个的区别有时间会详细的进行下统计。
下面的转义字符都可以用在 echo 中:
转义字符 | 含义 |
---|---|
\\ | 反斜杠 |
\a | 警报,响铃 |
\b | 退格(删除键) |
\f | 换页(FF),将当前位置移到下页开头 |
\n | 换行 |
\r | 回车 |
\t | 水平制表符(tab键) |
\v | 垂直制表符 |
二、变量的截取替换
表达式 | 含义 |
---|---|
${#string} | $string的长度 |
${string:position} | 在$string中, 从位置$position开始提取子串 |
${string:position:length} | 在$string中, 从位置$position开始提取长度为$length的子串 |
${string#substring} | 从变量$string的开头, 删除最短匹配$substring的子串 |
${string##substring} | 从变量$string的开头, 删除最长匹配$substring的子串 |
${string%substring} | 从变量$string的结尾, 删除最短匹配$substring的子串 |
${string%%substring} | 从变量$string的结尾, 删除最长匹配$substring的子串 |
${string/substring/replacement} | 使用$replacement, 来代替第一个匹配的$substring |
${string//substring/replacement} | 使用$replacement, 代替所有匹配的$substring |
${string/#substring/replacement} | 如果$string的前缀匹配$substring, 那么就用$replacement来代替匹配到的$substring |
${string/%substring/replacement} | 如果$string的后缀匹配$substring, 那么就用$replacement来代替匹配到的$substring |
接下来的实例进行讲解下这部分的命令:
#!/bin/sh
test="My name is WenXuechao and my first name is Wen"
echo "输出test的长度"
echo ${#test}
echo "从位置position处提取字符串"
echo ${test:11}
echo "从位置position开始提取长度为length的子串"
echo ${test:8:2}
echo "从变量string的开头, 删除最短匹配substring的子串"
echo ${test#*name}
echo "从变量string的开头, 删除最长匹配substring的子串"
echo ${test##*name}
echo "从变量string的结尾, 删除最短匹配substring的子串"
echo ${test%name*}
echo "从变量string的结尾, 删除最长匹配substring的子串"
echo ${test%%name*}
echo "使用replacement, 来代替第一个匹配的substring"
echo ${test/name/MingZi}
echo "使用replacement, 代替所有匹配的substring"
echo ${test//name/MingZi}
echo "如果string的前缀匹配substring, 那么就用replacement来代替匹配到的substring"
echo ${test/#*name/MingZi}
echo "如果string的后缀匹配substring, 那么就用replacement来代替匹配到的substring"
echo ${test/%name*/MingZi}
执行结果如下:
直接根据实例即可看到对应的执行方式。
灵活的运用shell截取,能够在服务器运维当中节省大量时间,包括对print的使用等命令,都能提供很多遍历,后续继续补充。