删除变量开头和结尾的子字符串匹配模式

问题描述:

正如标题所述,我正在寻找一种删除变量开头和结尾处已定义模式的方法.我知道我必须使用#%,但是我不知道正确的语法.

As the title says, I'm looking for a way to remove a defined pattern both at the beginning of a variable and at the end. I know I have to use # and % but I don't know the correct syntax.

在这种情况下,我想删除从file.txt读取的变量$line的开始处的http://和结尾处的/score/.

In this case, I want to remove http:// at the beginning, and /score/ at the end of the variable $line which is read from file.txt.

好吧,您不能嵌套${var%}/${var#}操作,因此必须使用临时变量.

Well, you can't nest ${var%}/${var#} operations, so you'll have to use temporary variable.

就像这里:

var="http://whatever/score/"
temp_var="${var#http://}"
echo "${temp_var%/score/}"

或者,您可以将正则表达式与(例如)sed一起使用:

Alternatively, you can use regular expressions with (for example) sed:

some_variable="$( echo "$var" | sed -e 's#^http://##; s#/score/$##' )"