Bash 中的参数替换
有时我们可能想从字符串中删除一个值或用一个新值替换它。有许多不同的方法可以做到这一点。
本文将解释如何为此目的使用 Linux Bash 脚本中的参数替换方法。
在 Linux Bash 中使用参数替换
Bash 参数替换是从字符串中删除或替换值的绝佳方法。本文的其余部分将解释我们如何通过示例来完成它们。
以下字符串将用于示例。
str="one two three two one"
从 Bash 中的字符串中删除表达式
有两种方法可以使用参数替换从字符串中删除表达式。
${string%expression}
命令删除 string
末尾的 expression
。在下面的示例中,str
中的最后一个 one
将被删除。
echo "${str%one}"
${string#expression}
命令删除 string
开头的 expression
。在下面的例子中,str
中的第一个 one
将被删除。
echo "${str#one}"
在 Bash 中替换字符串中的表达式
${string/expression/value}
命令将它在 string
中找到的第一个 expression
替换为 value
。在下面的示例中,str
中的第一个 one
将被替换为 four
。
echo "${str/one/four}"
${string//expression/value}
命令将它在 string
中找到的所有 expression
替换为 value
。在以下示例中,str
中的所有 one
单词都将替换为 four
。
echo "${str//one/four}"
${string/#expression/value}
命令将 string
开头的 expression
替换为 value
。在下面的示例中,str
中的第一个 one
将被替换为 four
。
echo "${str/#one/four}"
${string/%expression/value}
命令将 string
末尾的 expression
替换为 value
。在以下示例中,str
中的最后一个 one
将替换为 four
。
echo "${str/%one/four}"
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。