bash 中的字符串替换 (${s//$foo/$bar}) 不适用于反斜杠

标签 string bash scripting string-substitution

我的变量中有一个字符串,我想用另一个字符串替换它,但是当匹配的字符串包含反斜杠时,该操作无效。

这是脚本中不起作用的部分:

cpuQueueOutput=`/usr/local/nagios/libexec/check_nrpe -H $hostname -t 30 -c Check_Pdh -a 'counter=\System\Processor Queue Length'`
echo "CPU Queue1: $cpuQueueOutput"
matchCpuQueueOutput="\System\Processor"
newCpuQueueOutput="CPU Queue"
CpuQueuePerf=`echo ${cpuQueueOutput//$matchCpuQueueOutput/$newCpuQueueOutput}`
echo "CPU Queue2: $CpuQueuePerf"

脚本的输出如下所示:

CPU Queue1: OK: |'\System\Processor Queue Length_value'=0;0;0
CPU Queue2: OK: |'\System\Processor Queue Length_value'=0;0;0
OK: CPU Stats {(total, avg 1m: 9%), (total, avg 5m: 3%)} Top 3 Processes: {(powershell : 64%), (svchost#3 : 0%), (svchost#2 : 0%)} | 'total 1m'=9%;90;95 'total 5m'=3%;90;95

OK: |'\System\Processor Queue Length_value' 替换为 'CPU Queue' 不起作用。

最佳答案

使用更多引号!

# $'' makes the shell interpret backslashes, for easier embedding of single quotes
# inside a single-quoted string.
s=$'|\'\\System\\Processor Queue Length_value\'=0;0;0'
match="\System\Processor"
replace="CPU Queue"
echo "${s//"$match"/$replace}" # ignore StackOverflow's incorrect syntax highlighting

...相对于...

echo "${s//$match/$replace}"

这是有效的,因为在 bash 中的模式匹配上下文中引用扩展会产生该扩展文字的结果 - 并且反斜杠需要被视为文字以匹配自身。

关于bash 中的字符串替换 (${s//$foo/$bar}) 不适用于反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28195360/

相关文章:

linux - shell 脚本。我的脚本中的命令替换问题

python - 搜索并计算文本文件中带有特殊字符的特定短语

php - 在 PHP 中测试 UTF-8 字符串是一种可靠的方法吗?

string - String.TrimStart()无法正常运行,为什么?

linux - 如何在 shell 脚本中使用冒号从 mysql 中分离检索到的数据?

c++ - luabind 没有启动我定义的功能

c++ - 如何实现类似于 Microsoft Excel 的 "record macro"类功能?

java - 如何从字符串中获取数字和非数字值

bash - 如何将 'reset' bash 恢复为出厂设置 - MacOS Sierra

linux - Bash - 命令调用移植到内部有另一个变量的变量