从 Bash 中的字符串中删除固定前缀/后缀 [英] Remove a fixed prefix/suffix from a string in Bash

查看:32
本文介绍了从 Bash 中的字符串中删除固定前缀/后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 bash 脚本中,我有一个字符串及其前缀/后缀.我需要从原始字符串中删除前缀/后缀.

In my bash script I have a string and its prefix/suffix. I need to remove the prefix/suffix from the original string.

例如,假设我有以下值:

For example, let's say I have the following values:

string="hello-world"
prefix="hell"
suffix="ld"

如何得到以下结果?

result="o-wor"

推荐答案

$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor

这在 Shell 参数扩展 手册部分:

${parameter#word}
${parameter##word}

单词被扩展以产生一个模式并根据下面描述的规则进行匹配(参见 模式匹配).如果模式匹配参数扩展值的开头,则扩展的结果是参数的扩展值与最短匹配模式(# case)或最长匹配模式(## case) 删除.[…]

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. […]

${parameter%word}
${parameter%%word}

单词被扩展以产生一个模式并根据下面描述的规则进行匹配(参见 模式匹配).如果模式匹配参数扩展值的尾随部分,则扩展的结果是具有最短匹配模式(% 情况)或最长匹配模式(%% case) 删除.[…]

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. […]

这篇关于从 Bash 中的字符串中删除固定前缀/后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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