首页 > 解决方案 > Regex and Bash file - Extract data from another file and store in variable

问题描述

While I'm learning RegEX, I'm trying to build a bash script to extract data from a file and then store it in variables, so I can work with the stored values to automatize my script.

I know the existence of SED and GREP, but I'm not sure how to use them properly.

The value I need is in a file called: /path/to/config.inc.php

mysql://user:password@server/user_database

So while I was learning RegEX (using the https://regexr.com/ website to learn), I was able to create this RegEX Expression:

(mysql\:\/\/)(.+.)\:(.+.)@(.+.)\/(.+)

So basically I need the USER, PASSWORD and USER_DATABASE values to be stored in the script in variables like:

user = $2
password = $3
userdatabase = $5

So I could call the variables inside the bash script to automatize some stuff. What would be the best approach to that?

标签: regexbashshell

解决方案


You may use sed + read:

read un pw db < <(sed -En '
s#.*mysql://([^:]+):([^@]+)@[^/]+/([_[:alnum:]]+).*#\1 \2 \3#p' config.inc.php)

# check variable content

declare -p un pw db
declare -- un="user"
declare -- pw="password"
declare -- db="user_database"

RegEx Details:

  • .*mysql://: Match all text till mysql://
  • ([^:]+): Match 1+ non-colon character and capture in group #1
  • :: Match literal colon
  • ([^@]+): Match 1+ non-@ character and capture in group #2
  • @: Match literal @
  • [^/]+/: Match 1+ non-/ character followed by /
  • ([_[:alnum:]]+): Match 1+ word characters and capture in group #2
  • .*: Match any remaining text till end
  • Replacement is \1 \2 \3 which is username password database values in that sequence.

推荐阅读