POSIX Shell动态字符串的双引号转义实现问题
解决方案:POSIX Shell原生实现
以下是符合要求的some_function实现,通过逐字符遍历处理输入字符串:
some_function() { local input="$1" local output="" local backslash_count=0 local char for (( i=0; i<${#input}; i++ )); do char="${input:i:1}" if [ "$char" = "\\" ]; then ((backslash_count++)) output+="$char" elif [ "$char" = "\"" ]; then # 给当前双引号强制添加一层转义 output+="\\" output+="$char" backslash_count=0 else backslash_count=0 output+="$char" fi done printf '%s' "$output" }
测试验证
可以用以下命令测试功能:
# 测试示例1 string='abc"def' print_str "$(some_function "$string")" # 预期输出:"abc\"def" # 测试示例2 string='{ "json": "{ \"key\": \"value\" }" }' print_str "$(some_function "$string")" # 预期输出:"{ \"json\": \"{ \\\"key\\\": \\\"value\\\" }\" }" # 测试特殊案例 string='\\\"' print_str "$(some_function "$string")" # 预期输出:"\\\\\""
实现原理
- 遍历输入字符串的每个字符,维护反斜杠计数器
- 遇到反斜杠时,计数器递增并直接追加到输出
- 遇到双引号时,先添加一个转义反斜杠,再追加双引号,随后重置计数器
- 遇到其他字符时,直接追加到输出并重置计数器
该实现完全遵循POSIX Shell标准,不依赖任何外部工具,确保所有双引号都被额外添加一层转义,满足需求。
内容的提问来源于stack exchange,提问作者Ly Schaumberg
相关产品推荐
相关产品推荐

