删除变量开头和结尾的子字符串匹配模式 [英] Remove substring matching pattern both in the beginning and the end of the variable
本文介绍了删除变量开头和结尾的子字符串匹配模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所述,我正在寻找一种删除变量开头和结尾处已定义模式的方法.我知道我必须使用#
和%
,但是我不知道正确的语法.
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/$##' )"
这篇关于删除变量开头和结尾的子字符串匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文