时间:2021-05-22
复制代码 代码如下:
#!/bin/bash
my_name="jxq"
echo $my_name
echo ${my_name}
# ------------------------------------
# 字符串操作
# ------------------------------------
# 单引号字符串的限制,双引号没有这些限制:
# 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的
# 单引号字串中不能出现单引号(对单引号使用转义符后也不行)
name="will"
age=24
my_full_name='${name}${age}'
echo ${my_full_name}
my_full_name="${name}${age}"
echo ${my_full_name}
# 字符串拼接
echo ${name}${age}
# 字符串长度
echo ${#name} # 4
# substring
message="I want to be healthy"
echo ${message:2} # want to be health, 2是position
echo ${message:2:4} # want,2是position,4是len
# delete shortest match from front: ${string#substring}
echo ${message#*want}
# delete shortest match from back: ${string%substring}
echo ${message%healthy}
# delete longest match from front: ${string##substring}
echo ${message##*h}
# delete longest match from back: ${string%%substring}
echo ${message%%t*}
# find and replace: ${string/pattern/replacement}
book_name="Catch Eye Eye"
echo ${book_name/Eye/Cat}
# find and replace all match: ${string//pattern/replacement}
echo ${book_name//Eye/Cat}
file_path="/usr/local/bin"
# only replace when pattern match the beginning: ${string/#pattern/replacement}
echo ${file_path/#\/usr/tmp}
# only replace when pattern match the end: ${string/%pattern/replacement}
echo ${file_path/%bin/tmp}
# string index
stringZ=abcABC123ABCabc
echo `expr index "$stringZ" C12` # Mac OSX不支持expr
# ------------------------------------
# 语句
# ------------------------------------
# if
if true
then
echo "ok, true"
fi
# 写成一行
if true; then echo "ok"; fi
var='12'
if [ $var -eq 12 ]; then
echo "This is a numeric comparison if example"
fi
if [ "$var" = "12" ]; then
echo "This is a string if comparison example"
fi
if [[ "$var" = *12* ]]; then
echo "This is a string regular expression if comparison example"
fi
name="jxq"
if [ "$name" = "jxq" ]; then
echo "hello" $name
fi
# 循环语句
for item in `ls *.sh`
do
echo $item
echo "completed"
done
# 写成一行
for item in `ls *.sh`; do echo $item; echo "completed"; done;
counter=1
while :
do
echo "bee"
let "counter=$counter+1"
if [ $counter -eq 3 ]; then
break # break/continue与Java类似
fi
done
# Case语句
opt="install"
case "${opt}" in
"install" )
echo "install..."
exit
"update" )
echo "update..."
exit
*) echo "bad opt"
esac
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
之前也发过相关的文章。这里呢,推荐大家使用一些内置的函数。在编写shell程序时,经常会涉及到字符串相关操作。有许多命令语句,如awk,sed都能够做字符串各种
本文实例讲述了C语言字符串原地压缩的实现方法,对于学习字符串操作的算法设计有不错的借鉴价值。分享给大家供大家参考。具体方法如下:字符串原地压缩示例:"eeeee
编写程序,利用continue语句实现循环体过滤器,过滤“老鹰”字符串,并做相应的处理,但是放弃continue语句之后的所有代码。即若遇到“老鹰”字符串则进行
一、字符串基础知识字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。
仔细研读后学习了三个函数:eval:计算字符串中的表达式exec:执行字符串中的语句execfile:用来执行一个文件需注意的是,exec是一个语句,而eval