bash 如何使用 shell 脚本变量作为 sed 的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1178839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:20:43  来源:igfitidea点击:

How do you use shell script variables as arguments to sed?

bashshellscriptingvariablessed

提问by Swoogan

What I would like to do is something like the following:

我想做的是以下内容:

#!/bin/sh
EMAIL="-e 's/SOMETHING//g'"

somecommand | sed "$EMAIL"

But I get the following:

但我得到以下信息:

sed: -e expression #1, char 2: unknown command: `''

I've tried many variations. I know it just a matter of getting the string quoting right. The reason I'd like to do this is to break a long sed command up for readability. Should I just use a sed script-file (with the -f option) instead?

我尝试了很多变体。我知道这只是让字符串引用正确的问题。我想这样做的原因是为了提高可读性,将一个很长的 sed 命令分解。我应该只使用 sed 脚本文件(带有 -f 选项)吗?

UPDATE:

更新:

My actual script is a little more complex:

我的实际脚本有点复杂:

#!/bin/sh
EMAIL="-e s/SOME THING//g -e s/SOME THING ELSE//g ..."

somecommand | sed "$EMAIL"

After removing the single quotes I get:

删除单引号后,我得到:

sed: -e expression #1, char 18: unknown option to `s'

回答by William Pursell

For this type of quoting problem, you could do one of:

对于此类引用问题,您可以执行以下操作之一:

#!/bin/sh
SED_ARG="-e 's/SOMETHING//g'"
echo SOMETHING | eval sed "$SED_ARG"
echo SOMETHING | sed $SED_ARG

What's happening is that in your version, the shell is invoking sed with one argument (the string "-e 's/SOMETHING//g'"), but you want sed to be invoked with two arguments ("-e" and "'s/SOMETHING//g'"). Eval causes the shell to interpret the string the way you want, as does not quoting the argument so that word splitting occurs. Note that this sort of thing is pretty fragile.

发生的情况是,在您的版本中,shell 使用一个参数(字符串“-e 's/SOMETHING//g'”)调用 sed,但您希望使用两个参数(“-e”和“ 's/某物//g'")。Eval 使 shell 以您想要的方式解释字符串,因为不引用参数以便发生分词。请注意,这种东西非常脆弱。

回答by nik

Passing arguments into a sed scriptshows with an example of writing grep.

将参数传递到 sed 脚本显示了一个编写示例grep

#!/bin/sh
#File: sedgrep
sed -n 's/'""'/&/p'

grep can be done as,

grep 可以这样做,

sedgrep '[A-Z][A-Z]' <file

回答by blispr

This worked for me (surround with double quotes) :

这对我有用(用双引号括起来):

 env | sed -n /"$USERNAME"/p

回答by David Z

Remove the single quotes from the value of EMAIL.

从 的值中删除单引号EMAIL

EMAIL="-e s/SOMETHING//g"

回答by ennuikiller

remove the single quotes and it should work just fine

删除单引号,它应该可以正常工作

回答by Stephen Paul Lesniewski

Put everything in single quotes and let the shell eval it later when it's used.

将所有内容放在单引号中,并让 shell 稍后在使用时对其进行评估。

EMAIL='-e s/[email protected]//g'
EMAIL2='-e s/[email protected]//g;s/[email protected]//g'
echo "[email protected] [email protected] [email protected] [email protected]" | sed $EMAIL $EMAIL2