#! /bin/bash
# assignment
str="abc"
echo $str
# append
str="efg $str"
# subsutitution
str=$(echo $str | sed -e 's/.* /([a-zA-Z]/+/)$//1/')
echo $str
# strip
str="abc efg"
str=${str##* }
echo $str
# uppercase 2
str="abc"
str=$(echo $str | tr '[a-z]' '[A-Z]')
echo $(echo abc | sed 'y/[a-z]/[A-Z]/')
echo $str
# start with
str="abcdefg"
if [[ $str =~ ^abc ]]; then
echo start with abc
fi
# end with
if [[ $str =~ efg$ ]]; then
echo end with efg
fi
# length
echo "length of $str is ${#str}"
# substring
# ${x:start:length}
echo "$str[0:3] is ${str:0:3}"
echo "$str[3:4] is ${str:3:4}"
# join
OLD_IFS=$IFS
IFS=:
set -- a b c d e
x="$*"
echo "$x"
IFS=$OLD_IFS
# $1=sep $2..list of fields
string_join()
{
if [ $# -ge 2 ]; then
sep=$1
shift
res=$1
shift
while [ $# -ne 0 ]; do
res="$res$sep$1"
shift
done
echo $res
return 0
fi
return 1
}
string_join : 1 2 3 4 5
string_join ";" a "abc" efg
# index
# find abc in 123ababc, res is 5
pattern=abc
string=123ababc
# find $0 in $1
# returns -1 if not found otherwise return the index where $0 in $1
string_index()
{
case $1 in
"") index=0;;
$2)
x=${1%%"$2*"}
index=$((${#x}-1))
;;
*) index=-1
esac
echo $index
if [[ $index != -1 ]]; then
return 0
else
return 1
fi
}
if string_index a b > /dev/null; then
echo a in b
else
echo not found
fi
# swap case
x=aBcD
echo $x | tr '[a-zA-Z]' '[A-Za-z]'
# assignment
str="abc"
echo $str
# append
str="efg $str"
# subsutitution
str=$(echo $str | sed -e 's/.* /([a-zA-Z]/+/)$//1/')
echo $str
# strip
str="abc efg"
str=${str##* }
echo $str
# uppercase 2
str="abc"
str=$(echo $str | tr '[a-z]' '[A-Z]')
echo $(echo abc | sed 'y/[a-z]/[A-Z]/')
echo $str
# start with
str="abcdefg"
if [[ $str =~ ^abc ]]; then
echo start with abc
fi
# end with
if [[ $str =~ efg$ ]]; then
echo end with efg
fi
# length
echo "length of $str is ${#str}"
# substring
# ${x:start:length}
echo "$str[0:3] is ${str:0:3}"
echo "$str[3:4] is ${str:3:4}"
# join
OLD_IFS=$IFS
IFS=:
set -- a b c d e
x="$*"
echo "$x"
IFS=$OLD_IFS
# $1=sep $2..list of fields
string_join()
{
if [ $# -ge 2 ]; then
sep=$1
shift
res=$1
shift
while [ $# -ne 0 ]; do
res="$res$sep$1"
shift
done
echo $res
return 0
fi
return 1
}
string_join : 1 2 3 4 5
string_join ";" a "abc" efg
# index
# find abc in 123ababc, res is 5
pattern=abc
string=123ababc
# find $0 in $1
# returns -1 if not found otherwise return the index where $0 in $1
string_index()
{
case $1 in
"") index=0;;
$2)
x=${1%%"$2*"}
index=$((${#x}-1))
;;
*) index=-1
esac
echo $index
if [[ $index != -1 ]]; then
return 0
else
return 1
fi
}
if string_index a b > /dev/null; then
echo a in b
else
echo not found
fi
# swap case
x=aBcD
echo $x | tr '[a-zA-Z]' '[A-Za-z]'
本文通过一个具体的 Bash 脚本实例介绍了字符串操作的基本方法,包括赋值、追加、替换、截取、转换大小写、判断开头结尾、获取长度、提取子串、连接字符串、查找索引及交换大小写等常见操作。
1365

被折叠的 条评论
为什么被折叠?



