反斜杠字符的 Bash 参数扩展规则 [英] Bash parameter expansion rules for backslash character

查看:43
本文介绍了反斜杠字符的 Bash 参数扩展规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,我想使用 Shell 参数扩展.最初,我使用了以下构造:

I have a variable, and I want to replace every occurrence of backslash ('\') with double backslash ('\\') using Shell parameter expansion. Originally, I used the following construction:

$ var='\\a\b'
$ echo "${var//\\/\\\\}"
\\\\a\\b

这很好用,但它破坏了 vim 语法突出显示 - 显然,vim 无法处理 \\} 部分.因此,我决定将反斜杠存储在一个变量中并用于避免语法突出显示问题:

This works fine, but it breaks vim syntax highlighting - apparently, vim cannot handle \\} part. So, I decided to store backslash in a variable and use to to avoid syntax highlighting issues:

$ bsl='\'
$ echo "${var//$bsl/$bsl$bsl}"
\\a\b

令我惊讶的是,它不起作用,尽管它适用于任何字母数字符号.那么,也许我需要在变量中存储 2 个反斜杠?我们来试试:

To my surprise, it does not work, although it would work fine with any alphanumeric symbol. So, maybe I need to store 2 backslashes in a variable? Let's try it:

$ bsl='\\'
$ echo "${var//$bsl/$bsl$bsl}"
\\\\\\\\a\\\\b

现在,它从不工作变成了我需要的工作时间的两倍.最终,我发现实现预期结果并保留 vim 突出显示的唯一方法如下:

Now, it went from not working to working twice the time I need. Eventually, I found that the only way to achieve desired result and preserve vim highlighting is the following:

$ bsl='\'
$ echo "${var//\\/$bsl$bsl}"
\\\\a\\b

虽然我已经找到了解决问题的方法,但我的问题是:为什么参数扩展以这种方式使用反斜杠?对我来说,这种行为毫无意义.

While I already found a way to solve my issue, my question is: why parameter expansion works this way with a backslash? To me, such behavior makes no sense.

推荐答案

根据 Bash 手册,使用 ${parameter/pattern/string},模式被扩展以产生一个模式只是就像在路径名扩展中一样."引用变量将保护它免受路径名扩展和引号/反斜杠删除.

According to the Bash manual, with ${parameter/pattern/string}, "the pattern is expanded to produce a pattern just as in pathname expansion." Quoting the variable will protect it from pathname expansion and quote/backslash removal.

$ echo "${var//$bsl/$bsl$bsl}"
\\a\b
$ echo "${var//"$bsl"/$bsl$bsl}"
\\\\a\\b

无论如何,如果您使用的是 GNU 系统,您可以使用 printf %q 来获得类似的结果.

For what it's worth, if you're on a GNU system you could use printf %q to achieve a similar result.

$ printf '%q\n' "$var"
\\\\a\\b

这篇关于反斜杠字符的 Bash 参数扩展规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆