zsh sed用特殊字符扩展变量并保留它们

时间:2020-05-29 23:03:40

标签: macos awk sed special-characters zsh

我正在尝试将字符串存储在变量中,然后在sed命令中扩展该变量。

在调用命令之前,我要在变量中放入的几个值将带有括号(左括号前有斜杠,斜杠前没有斜杠),换行和其他特殊字符。另外,该字符串将在正在搜索的文件中用双引号引起来,我想用那些双引号将其仅限制为我要查询的字符串。

该命令必须能够与文件中的那些特殊字符匹配。使用zsh / Mac OS,尽管如果该命令与bash 4.2兼容,那将是一个不错的选择。回显xargs也很好。另外,如果awk对此更好,则我不需要使用sed。

类似...

sed 's/"\"$(echo -E - ${val})\""/"${key}.localized"/g' "${files}"

鉴于 $ val 是我上面所述的变量, $ key 没有空格(但带有下划线),而 $ files 是一个数组文件路径(最好与空格兼容,但不是必需的)。

$ val ...的示例输入值...

... "something \(customStringConvertible) here" ...

... "something (notVar) here" ...

... "something %@ here" ...

... "something @ 100% here" ...

... "something for $100.00" ...

示例输出:

... "some_key".localized ...

我正在使用sed命令替换上面的示例。我覆盖它的文本非常简单。

我遇到的关键问题是获取与特殊字符匹配的命令,而不是扩展它们然后尝试匹配。

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

awk更好,因为它提供了适用于文字字符串的函数:

$ val='something \(customStringConvertible) here' awk 'index($0,ENVIRON["val"])' file
... "something \(customStringConvertible) here" ...

$ val='something for $100.00' awk 'index($0,ENVIRON["val"])' file
... "something for $100.00" ...

上面是在此输入文件上运行的:

$ cat file
... "something \(customStringConvertible) here" ...
... "something (notVar) here" ...
... "something %@ here" ...
... "something @ 100% here" ...
... "something for $100.00" ...

使用sed,您必须按照Is it possible to escape regex metacharacters reliably with sed上的说明尝试伪造sed。

尚不清楚您的真正目标是什么,因此,如果需要更多帮助,请编辑问题以提供简洁,可测试的样本输入和预期输出。话虽如此,看来您正在进行替换,所以也许这就是您想要的:

$ old='"something for $100.00"' new='here & there' awk '
    s=index($0,ENVIRON["old"]) { print substr($0,1,s-1) ENVIRON["new"] substr($0,s+length(ENVIRON["old"])) }
' file
... here & there ...

或者,如果您愿意:

$ old='"something for $100.00"' new='here & there' awk '
    BEGIN { old=ENVIRON["old"]; new=ENVIRON["new"]; lgth=length(old) }
    s=index($0,old) { print substr($0,1,s-1) new substr($0,s+lgth) }
' file

或:

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; lgth=length(old) }
    s=index($0,old) { print substr($0,1,s-1) new substr($0,s+lgth) }
' '"something for $100.00"' 'here & there' file
... here & there ...

有关上述ENVIRON[]ARGV[]的使用方式,请参见How do I use shell variables in an awk script?