bobylapointe
bobylapointe

Reputation: 683

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.

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

Answers (5)

user80168
user80168

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

michael501
michael501

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

Charles Duffy
Charles Duffy

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

jaypal singh
jaypal singh

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

Gilles Quénot
Gilles Quénot

Reputation: 185790

You have to do it in 2 steps :

$ string="fooSTUFFfoo"
$ string="${string%foo}"
$ string="${string#foo}"
$ echo "$string"
STUFF

Upvotes: 5

Related Questions