str="abc123abcABC"
#计算字符串的长度
echo ${#str} #12
expr length $str
expr "$str" : ".*"
查找子串位置
expr index $str "b" #2
得到子字符串
代码:# 方法
[hadoop@localhost d3]$ expr substr "$str" 1 3
abc
[hadoop@localhost d3]$ expr substr "$str" 1 5
abc12
[hadoop@localhost d3]$ expr substr "$str" 2 5
bc123
#==取子串==
# ${string:position}
# ${string:positon:length}
echo ${str:2} #从第2个位置开始提取字符串的值,从0开始,c123abcABC
echo ${str:2:3} #从第2个位置开始提取长度为3个字符的值,c12
#反向提取子串
echo ${str:(-2)} #从反向的第2个位置开始提取字符串,BC
echo ${str:(-2):6} #从反向的第2个字符的位置开始提取长度为6个字符的串,BC
echo ${str:(-6):3} #6个中提出3个总可以了,abc
#=子串替换=
# ${string/substring/replacement}
# 使用$replacement来替换第一个匹配的$substring.
# ${string//substring/replacement}
# 使用$replacement来替换所有匹配的$substring.
#
# ${string/#substring/replacement}
# 如果$substring匹配$string的开头部分,那么就用$replacement来替换$substring.
# ${string/%substring/replacement}
# 如果$substring匹配$string的结尾部分,那么就用$replacement来替换$substring.
#
str1="123abcABCab12"
echo ${str1/12/hover} #仅仅替换了第一个,hover3abcABCab12
echo ${str1//12/hover} #替换了所有的,hover3abcABCabhover
echo ${str1/#12/hover} # 从头开始匹配12,如果找到做替换,hover3abcABCab12
echo ${str1/%12/hover} # 从尾开始匹配12,如果找到做替换,123abcABCabhover
匹配正则表达式
# 打印匹配长度
[hadoop@localhost d3]$ expr match $str "abc"
3
[hadoop@localhost d3]$ expr match $str "abcd"
0
[hadoop@localhost d3]$ expr match $str "abc12"
5
连接
[hadoop@localhost d3]$ echo $str$str1
123456789abc0000
得到字符串中某个字符的重复次数
[hadoop@localhost d3]$ str=11223456789
[hadoop@localhost d3]$ echo $str |tr "x" "\n" |wc -l得到的结果需要减去1
1
[hadoop@localhost d3]$ echo $str |tr "1" "\n" |wc -l
3
[hadoop@localhost d3]$ echo $str |awk -F"1" '{print NF-1}'
2
将一批文件中的所有string替换
for i in file_list
do
vi $i <<-!
:g/xxxx/s//XXXX/g
:wq
!
done
将字符串内每两个字符中间插入一个字符或多个字符
str=11223456789
[hadoop@localhost d3]$ echo $str |sed 's/../&[-]/g'
11[-]22[-]34[-]56[-]78[-]9
[hadoop@localhost d3]$ echo $str |sed 's/../&-/g'
11-22-34-56-78-9
应用字符串截断
该文件是否是一个tar文件。要确定它是否是 tar 文件,将在文件末尾查找模式 ".tar"。如下所示:
mytar.sh -- 一个简单的脚本
#!/bin/bash
if [ "${1##*.}" = "tar" ]
then
echo This is a tar file
else
echo This is not a tar file
fi
$ ./mytar.sh thisfile.tar
This is a tar file
$ ./mytar.sh thatfile.gz
This is not a tar file
"${1##*.}" 将从环境变量"1"包含的字符串开始部分除去最长的 "*." 匹配,并返回结果。这将返回文件中最后一个 "." 之后的所有部分。显然,如果文件以 ".tar" 结束,结果将是 "tar",条件也为真。
[hadoop@localhost d3]$ aa=aa.tar
[hadoop@localhost d3]$ echo ${aa##*.}
tar
2022-9-21