如何在bash中的字符串变量中阐明特殊语法字符

发布于 2025-02-07 16:19:56 字数 475 浏览 1 评论 0原文

给定:

一个字符串变量,包含bash用于扩展或作为定义者的字符,例如

> path="/this/path/contains whitespace/and/asterisk */myfile.txt"

目标:

我想在一个那些bash语法元素被拒绝(或禁用但不简单地引用)的方式,即解决方案的输出将是

> solution $path
/this/path/contains\ whitespace/and/asterisk\ \*/myfile.txt

问题:

不是bash中有一个命令可以做到这一点,而不是必须自己与所有特殊角色挣扎?

GIVEN:

A string variable containing characters that are used by bash for expansion or as delimiters, e.g.

> path="/this/path/contains whitespace/and/asterisk */myfile.txt"

GOAL:

I want to expand the variable in a way that those bash syntax elements are backslashed (or disabled but not simply quoted), i.e. the output of solution would be

> solution $path
/this/path/contains\ whitespace/and/asterisk\ \*/myfile.txt

QUESTION:

Isn't there a command in bash that does that, rather than having to struggle with all special characters on my own?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2025-02-14 16:19:56

使用%Q printf的指定符(bash indendin):

path="/this/path/contains whitespace/and/asterisk */myfile.txt"
printf '%q\n' "$path"

Use the %q specifier of printf (a bash builtin):

path="/this/path/contains whitespace/and/asterisk */myfile.txt"
printf '%q\n' "$path"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文