SED越狱用户输入字符串 [英] sed escape user input string
问题描述
我使用SED的字符串替换在配置文件中。
I am using sed for string replacement in a config file.
用户必须输入字符串盐
然后我替换配置文件本盐
字符串:
User has to input the string salt
and then I replace this salt
string in the config file:
Sample config file myconfig.conf
CONFIG_SALT_VALUE=SOME_DUMMY_VALUE
我用命令的值代替虚值盐
用户输入。
sed -i s/^CONFIG_SALT_VALUE.*/CONFIG_SALT_VALUE=$salt/g" ./myconfig.conf
问题的:值 $盐
可以包含任何字符,所以如果 $盐
包含 /
(如 12D / DFS
),那么我上面的sed命令中断。
Issue : value of $salt
can contain any character, so if $salt
contains /
(like 12d/dfs
) then my above sed command breaks.
我可以改变分隔符!
,但是现在如果再 $盐
包含 AMGH !FHF
然后我的sed命令将中断。
I can change delimiter to !
, but now again if $salt
contains amgh!fhf
then my sed command will break.
我应该如何着手这个问题?
How should I proceed to this problem?
推荐答案
您几乎可以使用任何字符作为 SED
分隔符。然而,正如你在你的问题提的,不断变化是脆弱的。
You can use almost any character as sed
delimiter. However, as you mention in your question, to keep changing it is fragile.
也许这是使用有用 AWK
代替,这样做行解析一点点:
Maybe it is useful to use awk
instead, doing a little bit of parsing of the line:
awk 'BEGIN{repl=ARGV[1]; ARGV[1]=""; FS=OFS="="}
$1 == "CONFIG_SALT_VALUE" {$2=repl}
1' "$salt" file
由于单行:
awk 'BEGIN{repl=ARGV[1]; ARGV[1]=""; FS=OFS="="} $1 == "CONFIG_SALT_VALUE" {$2=repl}1' "$salt" file
这集 =
作为字段分隔符。然后,它会检查,当行包含 CONFIG_SALT_VALUE
作为参数名称。发生这种情况时,它的值替换到给定的一个。
This sets =
as field separator. Then, it checks when a line contains CONFIG_SALT_VALUE
as parameter name. When this happens, it replaces the value to the one given.
要在 $盐prevent值
如 foo的\\\\栏
被间preTED ,因为其他人在我原来的答复评价说,我们有绝招:
To prevent values in $salt
like foo\\bar
from being interpreted, as that other guy commented in my original answer, we have the trick:
awk 'BEGIN{repl=ARGV[1]; ARGV[1]=""} ...' "$var" file
这将使用如何使用变量包括AWK特殊符号?哪里埃德莫顿说。
This uses the answer in How to use variable including special symbol in awk? where Ed Morton says that
的方式来传递一个shell变量,在awk没有被反斜杠
PTED间$ P $是把它传中,ARG列表,而不是填充一个awk
脚本变量之外。
The way to pass a shell variable to awk without backslashes being interpreted is to pass it in the arg list instead of populating an awk variable outside of the script.
然后
您需要设置 ARGV [1] =
填充awk的变量后,
避免壳变量值也被当作一个文件名。
不同于传入变量的任何其他方式,用于在所有的字符
一个变量这种方式,没有特殊的含义从字面上对待。
You need to set
ARGV[1]=""
after populating the awk variable to avoid the shell variable value also being treated as a file name. Unlike any other way of passing in a variable, ALL characters used in a variable this way are treated literally with no "special" meaning.
这不会做就地编辑,但你可以重定向到另一个文件中,然后替换原来的:
This does not do in-place editing, but you can redirect to another file and then replace the original:
awk '...' file > tmp_file && mv tmp_file file
这篇关于SED越狱用户输入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!