简体   繁体   中英

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

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?

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

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

Personally (so probably not the best choice), I would use cut for this:

PW=$(echo -e ${CONN} | cut -d":" -f3 | cut -d"@" -f1)

Running it yields:

Connection:    mysql://username:password1@hostname/database_name
Username:      password1

NOTE: If you're going to use \\ in echo make sure you use the -e option

The syntax you are trying to use:

awk '/username:/,/@/'

will find the LINES between a LINE containing username and a LINE containing @ . It is not intended to find a string between delimiters within a line. Try:

sed 's/.*username:\(.*\)@.*/\1/'

instead. It's not robust but it may be all you need for your specific input.

IMHO you should use @Ko2r's solution though.

Another Bash:

CONN="mysql://username:password1@hostname/database_name"
IFS=:@ read UN PW __ <<< "${CONN#*//}"
echo "$UN" ## Outputs username
echo "$PW" ## Outputs password1

Compatibility: Bash 2.05b or newer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM