在 sed -f 中使用变量(其中 sed 脚本在文件中而不是内联) [英] Using variables in sed -f (where sed script is in a file rather than inline)
问题描述
我们有一个进程可以使用包含 sed
命令的文件来改变管道输入.
We have a process which can use a file containing sed
commands to alter piped input.
我需要用变量值替换输入中的占位符,例如在我可以运行的单个 -e
类型的命令中;
I need to replace a placeholder in the input with a variable value, e.g. in a single -e
type of command I can run;
$ echo "Today is XX" | sed -e "s/XX/$(date +%F)/"
Today is 2012-10-11
但是我只能在文件中指定 sed
方面(然后将进程指向文件),例如一个名为 replacements.sed
的文件可能包含;
However I can only specify the sed
aspects in a file (and then point the process at the file), E.g. a file called replacements.sed
might contain;
s/XX/Thursday/
很明显;
$ echo "Today is XX" | sed -f replacements.sed
Today is Thursday
但是,如果我想使用环境变量或 shell 值,我找不到使其扩展的方法,例如如果 replacements.txt
包含;
If I want to use an environment variable or shell value, though, I can't find a way to make it expand, e.g. if replacements.txt
contains;
s/XX/$(date +%F)/
然后;
$ echo "Today is XX" | sed -f replacements.sed
Today is $(date +%F)
在文件文本中包含双引号只会打印双引号.
Including double quotes in the text of the file just prints the double quotes.
有谁知道可以在 sed
文件中使用变量的方法吗?
Does anyone know a way to be able to use variables in a sed
file?
推荐答案
这可能对你有用(GNU sed):
This might work for you (GNU sed):
cat <<\! > replacements.sed
/XX/{s//'"$(date +%F)"'/;s/.*/echo '&'/e}
!
echo "Today is XX" | sed -f replacements.sed
如果您没有 GNU sed,请尝试:
If you don't have GNU sed, try:
cat <<\! > replacements.sed
/XX/{
s//'"$(date +%F)"'/
s/.*/echo '&'/
}
!
echo "Today is XX" | sed -f replacements.sed | sh
这篇关于在 sed -f 中使用变量(其中 sed 脚本在文件中而不是内联)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!