If I have the following code:

twitter="https://twitter.com/username"

How do I use something like sed or awk to remove this:

https://twitter.com/

So I'm left with:

username
有帮助吗?

解决方案 2

The task can be accomplished by basename:

$ basename https://twitter.com/username
username

其他提示

Just use bash variable expansion:

$ twitter="https://twitter.com/username"
$ echo "${twitter##*/}"
username

## removes the longest match from the beginning of the string.

You don't need an external program, you can just use normal parameter substitution using the # to remove the prefix:

$ twitter="https://twitter.com/username"
$ echo ${twitter#https://twitter.com/}
username

Using BASH regex capability:

s="https://twitter.com/username"
[[ "$s" =~ /([^/]+)$ ]] && echo "${BASH_REMATCH[1]}"
username

For such a simple task regex might not be always needed but power of regex can be considered for more complex job like finding last but one string between slashes etc.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top