Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK: Trouble with AWK (print between two patterns) not working as expected

Tags:

regex

bash

awk

I've tried searching but have not found the answer I'm looking for. For this scenario, I have the following script:

#!/bin/bash

CONN="mysql://username:password1@hostname/database_name"

echo "Connection:\t${CONN}"

PW=$(echo ${CONN} |awk '/username:/,/@/')
echo "Username:\t${PW}"

I'm trying to set the new variable of PW to the value of password1.

Is there something I'm missing?

like image 745
Jeremy Avatar asked May 09 '26 07:05

Jeremy


2 Answers

You don't need awk here. Just BASH is good enough:

conn="mysql://username:password1@hostname/database_name"
[[ "$conn" =~ username:(.*)@ ]] && pw="${BASH_REMATCH[1]}"
echo "$pw"
password1
like image 119
anubhava Avatar answered May 11 '26 23:05

anubhava


Just do that :

 TMP="${CONN##*:}"                       //Delete all characters from the head till the last ':'
 CONN="${TMP%%@*}"                       //Delete all characters from the tail till the last '@'

and you have password1 in CON

like image 44
Ko2r Avatar answered May 12 '26 01:05

Ko2r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!