-1

I have a messy script which should get the name of the site (like https://google.com/etc):

#!/bin/bash ARTIST=$(echo "$@" | grep -oP 'https:\\/\\/\\K.+?(?=.com)' | sed -e "s/\b\(.\)/\u\1/g") echo $(echo "$@" | grep -oP 'https:\\/\\/\\K.+?(?=.com)' | sed -e "s/\b\(.\)/\u\1/g") echo "$ARTIST" echo "$@" 

And for some reason, $(...) doesn't return anything while running outside of the script works fine.

$ ./test.sh https://nothing.bandcamp.com/music https://nothing.bandcamp.com/music 

Expected behavior:

$ echo "https://nothing.bandcamp.com/music" | grep -oP 'https:\\/\\/\\K.+?(?=.com)' | sed -e "s/\b\(.\)/\u\1/g" Nothing.Bandcamp 

What am I doing wrong?

2
  • Please avoid using Pastebin at all costs on our site, thank you.CommentedMay 30, 2021 at 5:38
  • echo https://nothing.bandcamp.com/music | grep -oP 'https:\\/\\/\\K.+?(?=.com)' returns nothing, I just tested it, I'm no expert on regular expressions, so I will leave this question to others. Cheers.CommentedMay 30, 2021 at 6:06

1 Answer 1

2

You are escaping \ itself in your grep regular expression. i.e. your \\/ means a literal backslash followed by a forward slash, and \\K means a literal backslash followed by a capital K.

Also, / doesn't even need to be escaped with grep - that's only necessary when using / as a regex delimiter, as is the default with sed or perl (and, usually, it's better to just use another delimiter - like , or :, or =).

Use just plain un-escaped /, and \K instead. For example:

#!/bin/bash ARTIST=$(echo "$@" | grep -oP 'https://\K.+?(?=.com)' | sed -e 's/\b\(.\)/\u\1/g') echo "$ARTIST" 

Sample output:

$ ./test.sh https://nothing.bandcamp.com/music Nothing.Bandcamp $ echo "https://nothing.bandcamp.com/music" | grep -oP 'https://\K.+?(?=.com)' | sed -e 's/\b\(.\)/\u\1/g' Nothing.Bandcamp 

Note: this is as true when run on the command line as it is when run in a script.

e.g. the following produces no output, same as it would in a script:

$ echo "https://nothing.bandcamp.com/music" | grep -oP 'https:\\/\\/\\K.+?(?=.com)' | sed -e "s/\b\(.\)/\u\1/g" 
1
  • Welp, I'm using Fish Shell and it actually returns "Nothing.Bandcamp" while in bash it isn't. So, Fish was causing trouble.
    – Casual
    CommentedMay 31, 2021 at 9:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.