👨⚕️ 主页: gis分享者
👨⚕️ 感谢各位大佬 点赞👍 收藏⭐ 留言📝 加关注✅!
👨⚕️ 收录于专栏:Shell 面试

文章目录
- 一、🍀前言
-
- [1.1 ☘️字符串截取](#1.1 ☘️字符串截取)
- [1.2 ☘️字符串拼接](#1.2 ☘️字符串拼接)
- [1.3 ☘️知识扩展](#1.3 ☘️知识扩展)
一、🍀前言
在 Shell 脚本中,可以使用多种方法来实现字符串的截取和拼接。以下是一些常见的方法:
1.1 ☘️字符串截取
使用 Shell 内置变量:
通过 ${var:offset:length} 这种形式可以截取字符串。
powershell
str="Hello, World!"
# 截取前5个字符
echo ${str:0:5}
# 截取从第7个字符开始的子字符串
echo ${str:6}
# 截取从第7个字符开始的5个字符
echo ${str:6:5}
使用 cut 命令:
cut 命令可以根据字符、字节或字段来截取字符串。
powershell
# 截取前5个字符
echo "Hello, World!" | cut -c 1-5
使用 sed 命令:
sed 命令可以进行复杂的文本处理,包括截取字符串。
powershell
# 截取前5个字符
echo "Hello, World!" | sed 's/^\(.\{5\}\).*/\1/'
使用 awk 命令:
awk 命令也可以用于截取字符串。
powershell
# 截取前5个字符
echo "Hello, World!" | awk '{print substr($0, 1, 5)}'
1.2 ☘️字符串拼接
直接利用 Shell 的变量替换功能,通过简单的赋值操作来完成。
powershell
str1="Hello"
str2=", World!"
new_str="$str1$str2"
echo $new_str # 输出 "Hello, World!"
使用 printf 命令:
powershell
str1="Hello"
str2="World"
printf "%s %s\n" "$str1" "$str2" # 输出 "Hello World"
使用${}进行参数扩展的拼接:
powershell
name="world"
greeting="Hello, ${name}!"
echo "$greeting" # 输出 "Hello, world!"
使用awk进行更复杂的操作:
powershell
str1="Hello"
str2="World"
echo | awk "{print \"$str1\" \"$str2\"}" # 输出 "HelloWorld"(无空格)
1.3 ☘️知识扩展
字符串长度:
powershell
str="Hello, World!"
len=${#str}
echo $len # 输出 13
从特定字符开始截取:
powershell
str="Hello, World!"
sub_str=${str:7}
echo $sub_str # 输出 "World!"
从特定字符结尾开始截取:
powershell
str="Hello, World!"
sub_str=${str: -6}
echo $sub_str # 输出 "World!"
拼接多个字符串:
powershell
part1="Hello"
part2=" "
part3="World"
full_str="$part1$part2$part3!"
echo $full_str # 输出 "Hello World!"
使用命令替换进行拼接:
使用命令替换(如 $(command))来动态生成部分字符串并进行拼接。
powershell
user=$(whoami)
date=$(date '+%Y-%m-%d')
welcome_str="Hello $user, today is $date."
echo $welcome_str # 输出 "Hello <用户名>, today is <日期>."