前言:
shell是一个命令解释器,它通过接受用户输入的Shell命令来启动、暂停、停止程序的运行或对计算机进行控制;shell脚本就是由Shell命令组成的执行文件,将一些命令整合到一个文件中,进行处理业务逻辑,脚本不用编译即可运行。
1 字符串拼接:
(1)变量拼接字符串
temp1=ABC
temp2=DEF
echo $temp1"123"
输出:ABC123
echo ${temp1}123
输出:ABC123
(2)变量结果拼接引号
echo "$temp2"
输出:DEF
echo '$temp2'
输出:$temp2 #单引号内部变量会被当做字符串
echo "\"$temp1\""
输出:"ABC" #先用双引号,然后内部的双引号使用反斜杠转义
echo "'${temp2}'"
输出:'DEF' #用双引号括起来的语句里面单引号变成纯粹的单引号
2 获取字符串长度:
#在${}中使用“#”获取长度
temp1=ABC
temp2=DE
echo ${#temp1}
输出:3
echo ${#temp2}
输出:2
3 提取子字符串:
temp=ABCD
echo ${temp:1:2}
#从第2个开始,往后截取2个字符
输出:BC
echo ${temp::2}
#第一个字符开始,往后截取2个字符
输出:AB
4 输入输出重定向:
shelltest.sh < file
将脚本的输入重定向到file,由file提供参数
shelltest.sh > file
将脚本的输出数据重定向到file中,覆盖数据
shelltest.sh >> file
将脚本的输出数据重定向到file中,追加数据
command >> file 2>&1
将 stdout 和 stderr 合并后重定向到file
5 字符替换:
#sed -i "s/原字符串/新字符串/g" `grep 原字符串 -rl 所在目录`
sed -i "s/oldStr/newStr/g" `grep oldStr -rl /path`
参考资料:
https://www.csdn.net/tags/NtTacg2sNzMzNTctYmxvZwO0O0OO0O0O.html shell中变量拼接输出字符串、单引号、双引号
http://www.cppcns.com/os/linux/313062.html 一篇教会你写90%的shell脚本(入门小结)
https://blog.csdn.net/weixin_42636454/article/details/116660247 使用sed命令批量替换文件夹中文件中的指定字符