字符串截取 #

一、使用参数扩展 #

1.1 基本截取 #

bash
#!/bin/bash

str="Hello World"

# 从指定位置开始
echo ${str:6}          # 输出: World

# 截取指定长度
echo ${str:0:5}        # 输出: Hello

# 从右边开始
echo ${str: -5}        # 输出: World
echo ${str:(-5)}       # 输出: World

1.2 使用变量 #

bash
#!/bin/bash

str="Hello World"
start=6
len=5

echo ${str:start:len}  # 输出: World
echo ${str:start}      # 输出: World

二、使用expr #

bash
#!/bin/bash

str="Hello World"

# expr substr 字符串 起始位置 长度
expr substr "$str" 1 5   # 输出: Hello
expr substr "$str" 7 5   # 输出: World

三、使用cut #

bash
#!/bin/bash

str="Hello World"

# 按字符位置
echo "$str" | cut -c1-5    # 输出: Hello
echo "$str" | cut -c7-11   # 输出: World

# 按分隔符
csv="a,b,c,d"
echo "$csv" | cut -d',' -f2  # 输出: b

四、使用awk #

bash
#!/bin/bash

str="Hello World"

# 使用substr函数
echo "$str" | awk '{print substr($0, 1, 5)}'  # 输出: Hello

# 按字段
echo "$str" | awk '{print $1}'  # 输出: Hello

五、实战示例 #

bash
#!/bin/bash

# 提取文件名和扩展名
file="document.pdf"
filename=${file%.*}
extension=${file##*.}
echo "文件名: $filename, 扩展名: $extension"

# 提取URL各部分
url="https://example.com/path/to/page"
protocol=${url%%:*}
domain=${url#*//}
domain=${domain%%/*}
echo "协议: $protocol, 域名: $domain"

六、总结 #

6.1 截取方法对比 #

方法 语法 特点
参数扩展 $ Bash内置,推荐
expr expr substr 兼容性好
cut cut -c 按字符位置
awk substr() 功能强大

6.2 下一步 #

你已经掌握了字符串截取,接下来让我们学习 字符串替换

最后更新:2026-03-27