You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效从文件读取的字符串中提取子串存入Bash变量

简化LDAP dn字符串中uid的提取代码

要从格式类似dn: uid=myUid,ou=People,dc=mydomain,dc=furtherdomain的字符串里提取uid对应的取值,你原来的代码用了多次冗余的字符串截取操作,下面提供几种更简洁的实现方式:

方法1:简化bash参数扩展写法

利用bash的参数扩展特性,两步就能完成截取,无需多次赋值:

#!/bin/bash

while IFS= read -r line; do
    if [[ "$line" == *"uid="* ]]; then
        uid=${line#*uid=}  # 移除"uid="之前的所有内容
        uid=${uid%,*}      # 移除第一个逗号及之后的所有内容
        echo "$uid"
    fi
done <<< "dn: uid=myUid,ou=People,dc=mydomain,dc=furtherdomain"

方法2:用awk直接提取字段

把=和,设为字段分隔符,直接定位到uid对应的值:

#!/bin/bash

while IFS= read -r line; do
    if [[ "$line" == *"uid="* ]]; then
        uid=$(echo "$line" | awk -F'[=,]' '{print $2}')
        echo "$uid"
    fi
done <<< "dn: uid=myUid,ou=People,dc=mydomain,dc=furtherdomain"

如果是直接处理文件,还能省去while循环,直接用awk遍历:

awk -F'[=,]' '/uid=/ {print $2}' your_file.txt

方法3:用sed正则捕获目标内容

通过sed的正则替换功能,精准捕获uid=到第一个逗号之间的内容:

#!/bin/bash

while IFS= read -r line; do
    if [[ "$line" == *"uid="* ]]; then
        uid=$(echo "$line" | sed -n 's/.*uid=\([^,]*\),.*/\1/p')
        echo "$uid"
    fi
done <<< "dn: uid=myUid,ou=People,dc=mydomain,dc=furtherdomain"

处理文件时同样可以直接调用sed:

sed -n 's/.*uid=\([^,]*\),.*/\1/p' your_file.txt

内容的提问来源于stack exchange,提问作者Eric Fetzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 19:12:36