bob*_*nte 19 string variables bash
正如标题所说,我正在寻找一种方法来在变量的开头和结尾处删除已定义的模式.我知道我必须使用#,%但我不知道正确的语法.
在这种情况下,我想http://在读取/score/的变量的开头和结尾处删除.$linefile.txt
小智 21
好吧,你不能嵌套${var%}/ ${var#}操作,所以你必须使用临时变量.
像这儿:
var="http://whatever/score/"
temp_var="${var#http://}"
echo "${temp_var%/score/}"
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用正则表达式(例如)sed:
some_variable="$( echo "$var" | sed -e 's#^http://##; s#/score/$##' )"
Run Code Online (Sandbox Code Playgroud)
$ var='https://www.google.com/keep/score'
$ var=${var#*//} #removes stuff upto // from begining
$ var=${var%/*} #removes stuff from / all the way to end
$ echo $var
www.google.com/keep
Run Code Online (Sandbox Code Playgroud)
您必须分两步完成:
$ string="fooSTUFFfoo"
$ string="${string%foo}"
$ string="${string#foo}"
$ echo "$string"
STUFF
Run Code Online (Sandbox Code Playgroud)