字符串替换 #

一、参数扩展替换 #

bash
#!/bin/bash

str="hello world world"

# 替换第一个匹配
echo ${str/world/WORLD}    # 输出: hello WORLD world

# 替换所有匹配
echo ${str//world/WORLD}   # 输出: hello WORLD WORLD

# 替换开头匹配
echo ${str/#hello/HELLO}   # 输出: HELLO world world

# 替换结尾匹配
echo ${str/%world/WORLD}   # 输出: hello world WORLD

二、使用sed #

bash
#!/bin/bash

str="hello world world"

# 替换第一个
echo "$str" | sed 's/world/WORLD/'     # 输出: hello WORLD world

# 替换所有
echo "$str" | sed 's/world/WORLD/g'    # 输出: hello WORLD WORLD

# 忽略大小写
echo "Hello WORLD" | sed 's/hello/hi/i'  # 输出: hi WORLD

# 使用正则表达式
echo "abc123def" | sed 's/[0-9]*/NUM/'   # 输出: NUMdef

三、使用tr #

bash
#!/bin/bash

# 字符替换
echo "hello" | tr 'a-z' 'A-Z'   # 输出: HELLO

# 删除字符
echo "hello123" | tr -d '0-9'   # 输出: hello

# 压缩重复字符
echo "hello    world" | tr -s ' '  # 输出: hello world

四、使用awk #

bash
#!/bin/bash

str="hello world world"

# 使用gsub全局替换
echo "$str" | awk '{gsub("world", "WORLD"); print}'
# 输出: hello WORLD WORLD

# 使用sub替换第一个
echo "$str" | awk '{sub("world", "WORLD"); print}'
# 输出: hello WORLD world

五、实战示例 #

bash
#!/bin/bash

# 批量替换文件内容
replace_in_file() {
    local file="$1"
    local old="$2"
    local new="$3"
    
    sed -i "s/$old/$new/g" "$file"
}

# 模板变量替换
render_template() {
    local template="$1"
    local -A vars="$2"
    
    local result="$template"
    for key in "${!vars[@]}"; do
        result="${result//\{\{$key\}\}/${vars[$key]}}"
    done
    
    echo "$result"
}

# 使用示例
template="Hello {{name}}, welcome to {{city}}!"
declare -A data
data[name]="张三"
data[city]="北京"

result=$(render_template "$template" data)
echo "$result"

六、总结 #

6.1 替换方法对比 #

方法 适用场景 特点
$ 简单替换 Bash内置
sed 复杂替换 支持正则
tr 字符映射 单字符替换
awk 文本处理 功能强大

6.2 下一步 #

你已经掌握了字符串替换,接下来让我们学习 数组基础

最后更新:2026-03-27