Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash extract after substring and before substring

Say I have a string:

random text before authentication_token = 'pYWastSemJrMqwJycZPZ', gravatar_hash = 'd74a97f

I want a shell command to extract everything after "authentication_token = '" and before the next '.

So basically, I want to return pYWastSemJrMqwJycZPZ.

How do I do this?

like image 790
Bik Avatar asked May 10 '26 09:05

Bik


1 Answers

Use parameter expansion:

#!/bin/bash
text="random text before authentication_token = 'pYWastSemJrMqwJycZPZ', gravatar_hash = 'd74a97f"
token=${text##* authentication_token = \'}   # Remove the left part.
token=${token%%\'*}                          # Remove the right part.
echo "$token"

Note that it works even if random text contains authentication token = '...'.

like image 126
choroba Avatar answered May 13 '26 01:05

choroba