加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用负偏移量在bash中使用字符串的后缀?

发布时间:2020-12-15 18:45:38 所属栏目:安全 来源:网络整理
导读:我试图使用${string:pos} substring语法在 Bash中使用字符串的后缀,但是我无法弄清楚为什么它不起作用.我已经设法简化了我的示例代码: STRING="hello world"POS=4echo ${STRING:POS} # prints "o world"echo ${STRING:4} # prints "o world"POS=-4echo ${S
我试图使用${string:pos} substring语法在 Bash中使用字符串的后缀,但是我无法弄清楚为什么它不起作用.我已经设法简化了我的示例代码:
STRING="hello world"

POS=4
echo ${STRING:POS} # prints "o world"
echo ${STRING:4}   # prints "o world"

POS=-4
echo ${STRING:POS} # prints "orld"
echo ${STRING:-4}  # prints "hello world"

前三行完全按照我的预期,但为什么最后一行打印“你好世界”而不是“orld”?

因为: – 是参数扩展语法为“使用默认值”.

从documentation:

When not performing substring expansion,using the form described
below (e.g.,‘:-’),Bash tests for a parameter that is unset or
null.

所以通过${STRING:-4}你实际上是要求bash来扩展
STRING,如果未设置(从未分配过)或为null
(一个空字符串,打印为”),它将替换为
在您的示例中,STRING已设置,因此将其扩展为其值.

正如另一个答案所说,你需要把表情看成没有
触发默认值行为,手册指定:

Note that a negative offset must be separated from the colon by at
least one space to avoid being confused with the :- expansion.

例如:

${STRING:(-4)}
${STRING: -4}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读