" SED"特殊字符处理

" SED"特殊字符处理

问题描述:

我们在脚本中有一个sed命令来替换值的文件内容从变量

we have an sed command in our script to replace the file content with values from variables

例如..

export value="dba01upc\Fusion_test"
sed -i "s%{"sara_ftp_username"}%$value%g" /home_ldap/user1/placeholder/Sara.xml

sed命令忽略特殊字符,例如\\和字符串dba01upcFusion_test更换没有'\\'
它的工作原理如果我做了类似的出口出口金额='dba01upc \\ Fusion_test'(与'\\'包围'')..但不幸的是我们的客户希望原文出口dba01upc \\ Fusion_test单/双引号,他不要不想给任何额外的字符添加到文本。
任何一个可以让我知道如何使SED放置文本有特殊字符。

the sed command ignores the special characters like '\' and replacing with string "dba01upcFusion_test" without '\' It works If I do the export like export value='dba01upc\Fusion_test' (with '\' surrounded with ‘’).. but unfortunately our client want to export the original text dba01upc\Fusion_test with single/double quotes and he don’t want to add any extra characters to the text. Can any one let me know how to make sed to place the text with special characters..

替换前:Sara.xml

Before Replacement : Sara.xml

<?xml version="1.0" encoding="UTF-8"?>
<ser:service-account >
<ser:description/>
<ser:static-account>
<con:username>{sara_ftp_username}</con:username>
</ser:static-account>
</ser:service-account>

置换后:Sara.xml

After Replacement : Sara.xml

<?xml version="1.0" encoding="UTF-8"?>
<ser:service-account>
<ser:description/>
<ser:static-account>
<con:username>dba01upcFusion_test</con:username>
</ser:static-account>
</ser:service-account>

在此先感谢

您不能有力地解决这个问题,SED。只需使用AWK来代替:

You cannot robustly solve this problem with sed. Just use awk instead:

awk -v old="string1" -v new="string2" '
idx = index($0,old) {
    $0 = substr($0,1,idx-1) new substr($0,idx+length(old))
}
1' file

啊,@ mklement0好点 - 从被间preTED您需要的值传递在阿根廷名单与文件名一起,然后从指定的变量,而不是赋值停止越狱与 -v 的变量(参见我写了很久以前的comp.unix.shell常见问题解答的 http://cfajohnson.com/shell/cus-faq-2.html#Q24 但显然已经忘了!)。

Ah, @mklement0 has a good point - to stop escapes from being interpreted you need to pass in the values in the arg list along with the file names and then assign the variables from that, rather than assigning values to the variables with -v (see the summary I wrote a LONG time ago for the comp.unix.shell FAQ at http://cfajohnson.com/shell/cus-faq-2.html#Q24 but apparently had forgotten!).

下面将有力地进行所需的替换( A \\ TA - > 电子\\ TF )的每一个搜索在每一行中找到字符串:

The following will robustly make the desired substitution (a\ta -> e\tf) on every search string found on every line:

$ cat tst.awk
BEGIN {
    old=ARGV[1]; delete ARGV[1]
    new=ARGV[2]; delete ARGV[2]
    lgthOld = length(old)
}
{
    head = ""; tail = $0
    while ( idx = index(tail,old) ) {
        head = head substr(tail,1,idx-1) new
        tail = substr(tail,idx+lgthOld)
    }
    print head tail
}

$ cat file
a\ta    a       a       a\ta

$ awk -f tst.awk 'a\ta' 'e\tf' file
e\tf    a       a       e\tf

的空白文件是标签。您可以转移ARGV [3]下来,如果你喜欢调整ARGC,但它没有必要在大多数情况下。

The white space in file is tabs. You can shift ARGV[3] down and adjust ARGC if you like but it's not necessary in most cases.