Reputation: 683
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.
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
.
Upvotes: 34
Views: 56317
Reputation:
Well, you can't nest ${var%}
/${var#}
operations, so you'll have to use temporary variable.
Like here:
var="http://whatever/score/"
temp_var="${var#http://}"
echo "${temp_var%/score/}"
Alternatively, you can use regular expressions with (for example) sed:
some_variable="$( echo "$var" | sed -e 's#^http://##; s#/score/$##' )"
Upvotes: 36
Reputation: 1482
how about
export x='https://www.google.com/keep/score';
var=$(perl -e 'if ( $ENV{x} =~ /(https:\/\/)(.+)(\/score)/ ) { print qq($2);}')
Upvotes: 0
Reputation: 295825
There IS a way to do it one step using only built-in bash functionality (no running external programs such as sed
) -- with BASH_REMATCH
:
url=http://whatever/score/
re='https?://(.*)/score/'
[[ $url =~ $re ]] && printf '%s\n' "${BASH_REMATCH[1]}"
This matches against the regular expression on the right-hand side of the =~
test, and puts the groups into the BASH_REMATCH
array.
That said, it's more conventional to use two PE expressions and a temporary variable:
shopt -s extglob
url=http://whatever/score/
val=${url#http?(s)://}; val=${val%/score/}
printf '%s\n' "$val"
...in the above example, the extglob
option is used to allow the shell to recognized "extglobs" -- bash's extensions to glob syntax (making glob-style patterns similar in power to regular expressions), among which ?(foo)
means that foo
is optional.
By the way, I'm using printf
rather than echo
in these examples because many of echo
's behaviors are implementation-defined -- for instance, consider the case where the variable's contents are -e
or -n
.
Upvotes: 3
Reputation: 77185
$ 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
Upvotes: 17
Reputation: 185790
You have to do it in 2 steps :
$ string="fooSTUFFfoo"
$ string="${string%foo}"
$ string="${string#foo}"
$ echo "$string"
STUFF
Upvotes: 5