regex - 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 tillmysql://
([^:]+)
: 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 isusername password database
values in that sequence.
推荐阅读
- python - Flask-restful:请求返回错误值
- terraform - Terraform:识别最新/最后创建的资源?
- rest - Show Swagger validation information
- d3.js - 如何在客户端使用使用 d3node 开发的图表或图形
- wpf - WPF 在应用程序启动时加载 texbox 内容
- sql-server - 非唯一索引与全表扫描
- c++ - 在 QObject 之外使用 QTimer
- python - multiprocess.Queue.get() 在 python 中需要很长时间
- java - Android Studios breakiterator,仅使用空格来中断文本
- android - 为什么我不能在 Android N+ 中附加文件?