1.变量替换
example1:根据匹配规则删除变量部分内容
example2:根据匹配规则替换变量部分内容
2.字符串处理
注意: ${}计算索引是从0开始 expr计算索引是从1开始。
3.关于字符串的完整脚本实例
#!/bin/bash
string="Bigdata process framework is Hadoop,Hadoop is an open source project"
function tips_info
{
echo "*********************************"
echo "*** (1) 打印string长度"
echo "*** (2) 在整个字符串中删除Hadoop"
echo "*** (3) 替换第一个Hadoop为Mapreduce"
echo "*** (4) 替换全部Hadoop为Mapreduce"
echo "*********************************"
}
function print_len
{
if [ -z "$string" ];then
echo "Error,string is null"
exit 1
else
echo "${#string}"
fi
}
function del_hadoop
{
if [ -z "$string" ];then
echo "Error,string is null"
exit 1
else
echo "${string//hadoop/}"
fi
}
function rep_hadoop_mapreduce_first
{
if [ -z "$string" ];then
echo "Error,string is null"
exit 1
else
echo "${string/Hadoop/Mapreduce}"
fi
}
function rep_hadoop_mapreduce_all
{
if [ -z "$string" ];then
echo "Error,string is null"
exit 1
else
echo "${string//Hadoop/Mapreduce}"
fi
}
while true
do
echo "[string=\"$string\"]"
tips_info
read -p "please Switch a Choice: " choice
case "$choice" in
1)
echo
echo "Length Of String is:`print_len`"
echo
continue
;;
2)
echo
echo "删除Hadoop后的字符串为:`del_hadoop`"
;;
3)
echo
echo "替换第一个Hadoop后的字符串为:`rep_hadoop_mapreduce_first`"
;;
4)
echo
echo "替换全部的Hadoop后的字符串为:`rep_hadoop_mapreduce_all`"
;;
q|Q)
exit 0
;;
*)
echo "error,unlegal input,legal input only in { 1|2|3|4|q|Q }"
continue
;;
esac
done
4.命令替换
命令替换:将某一个变量的输出结果作为另一变量的一部分
语法格式:
1. `command`
2.$(command)
例1-获取配置文件中的配置名
配置文件如下所示
[hadoop]
username=12231
hadoop_client=12231
hadoop_output=12231
python_interpreter=pypy
queue_name=12231
hadoop_client_tianqi=12231
hadoop_output_tianqi=12231
queue_name_tianqi=12231
sql_client=/home/work/songhzwg/mysql/mysql-5.1.49/client/mysql
[email]
send_mail=true
#!/bin/bash
#打印配置文件的配置名
index=1
for conf_name in `cat ~/Desktop/config.conf | cut -d "=" -f 1`
do
echo "This is $index config name: $conf_name"
index=$((index + 1))
done
输出如下结果:
This is 1 config name: [hadoop]
This is 2 config name: username
This is 3 config name: hadoop_client
This is 4 config name: hadoop_output
This is 5 config name: python_interpreter
This is 6 config name: queue_name
This is 7 config name: hadoop_client_tianqi
This is 8 config name: hadoop_output_tianqi
This is 9 config name: queue_name_tianqi
This is 10 config name: sql_client
This is 11 config name: [email]
This is 12 config name: send_mail
知识点:1.命令替换 2.cut(-d 指定分割名 -f指定分割后的结果列表索引)
例2-根据系统时间计算今年或明年
echo "Next year is $((`date +%Y` + 1))"
5.有类型变量
declare 声明变量类型
declare -r 声明变量为只读类型 eg:declare -r var="hello"
declare -i 声明变量为整形
declare -f 显示系统自定义的函数和内容
declare -F 显示定义的函数
declare -a array 声明一个数组
array=("jones" "mike" "kobe" "jordan")
1.输出数组内容:
echo ${array[@]} 输出全部内容
echo ${array[1]} 输出下标索引为1的内容
2.获取数组长度
echo ${#array}
3.赋值
array[0]="lily"
array[20]="hanmeimei"
4.删除元素
unset array[2]
unset array 清空整个数组
5.切片访问
${array[@]:1:4} 索引1到3的元素
6.数组遍历
for v in ${array[@]}
do
echo $v
done