Bash 扩展变量正确包含 sed 模式 [英] Bash expand variable containing sed pattern correctly
本文介绍了Bash 扩展变量正确包含 sed 模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的脚本:
#!/bin/bash
xx="-e \"s|a|b|g\""
sed -i $xx file
但是 sed 因消息而中断:
But sed breaks with message:
sed: -e expression #1, char 1: unknown command: `"'
使用 set -x
我可以看到命令被扩展为 sed -i -e '"s|a|b|g"' 文件
,所以我想双引号是它不起作用的原因.
Using set -x
I can see that the command is being expanded to sed -i -e '"s|a|b|g"' file
, so I guess the double quotes are why it is not working.
如何解决这个问题?
推荐答案
我不确定你为什么要做你正在做的事情,但我认为这可能会有所帮助:
I'm not sure exactly why you want to do what you're doing but I think that this might help:
$ cat file
a a
$ xx=( -e 's|a|b|g' -e 's|b|c|g' )
$ sed "${xx[@]}" file
c c
使用数组将每个参数存储到 sed.使用 "${xx[@]}"
安全地扩展数组,将每个元素作为单个参数传递.
Use an array to store each argument to sed. Use "${xx[@]}"
to safely expand the array, passing each element as a single argument.
您可以像这样构建数组:
You can build up the array like this:
$ xx=()
$ xx+=( -e 's|a| b c |g' )
$ xx+=( -e 's|c| d |g' )
$ sed "${xx[@]}" file
b d b d
这篇关于Bash 扩展变量正确包含 sed 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文