1

I'm making functions in my zshrc file to help me navigate to certain frequently visited webpages. For instance, calling 61b would open https://sp21.datastructur.es/, 61b lab6 would open https://sp21.datastructur.es/materials/lab/lab6/lab6, and 61b proj2 would open https://sp21.datastructur.es/materials/proj/proj2/proj2. I need to somehow create a substring of lab6 or proj2 so that I can use lab or proj in the URL.

function 61b() {
  if [ -n "$1" ]; then
    open https://sp21.datastructur.es/materials/??/$1/$1
  else
    open https://sp21.datastructur.es/
  fi
}

What would I put in the ??. I've tried just about everything.

1 Answer 1

1

You can perform many string operations by using more elaborate forms of parameter expansion of the form ${stuffPARAM} or ${PARAMstuff} (or combinations of them).

For example, ${1%%[0-9]##} is the first parameter ($1) with the digits (wildcard pattern [0-9]##) removed at the end (${…%%…}). You need to have setopt extended_glob in order for the wildcard pattern [0-9]## to work; put that in your .zshrc or in the function:

function 61b() {
  setopt local_options extended_glob unset
  if [ -n "$1" ]; then
    open https://sp21.datastructur.es/materials/${1%%[0-9]##}/$1/$1
  else
    open https://sp21.datastructur.es/
  fi
}

Instead of [0-9]##, you can use <->, which stands for a number in any range. (“Number” meaning a non-negative integer written in decimal, so it's equivalent to a sequence of digits.)

3
  • 1
    @StéphaneChazelas I doubt that https://sp21.datastructur.es/materials/// isn't useful, so I think thatreating empty as unset is the most useful behavior, in addition to being the simplest behavior to explain (since the asker already understands it). Feb 25, 2021 at 15:54
  • 1
    Ah, yes, I inverted the option, thanks. Feb 25, 2021 at 15:58
  • 1
    Or make it: 61b() open https://sp21.datastructur.es/${1:+materials/${1%%<->}/$1/$1} Feb 25, 2021 at 16:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .