简体   繁体   中英

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?

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.

While the answer with regex is absolutely fine, I think there is another simplier approach to consider. (And I love regex BTW).

Consider this:

mysql://user:password@server/user_database

cut -d"@" -f1

mysql://user:password

cut -d"/" -f3

user:password

cut -d":" -f1

user

The thing is, regex are really cool and useful but can be really hard to understand and maintain for any other person than yourself.

There is a joke going something along these lines:

Have a problem? Use regex to solve it! Now you have two problems ;)

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