1. 程式人生 > 實用技巧 >Linux shell如何用正則表示式匹配分組資料

Linux shell如何用正則表示式匹配分組資料

方法

兩種方法:grep和sed

echo "libgcc-4.8.5-4.h5.x86_64.rpm" | grep -Eo "[0-9]+\.[0-9]+.*x86_64"
echo "libgcc-4.8.5-4.h5.x86_64.rpm" | sed -r "s/libgcc-([0-9]+\.[0-9]+.*)\.rpm/\1/g"

轉載:https://www.cnblogs.com/jmliao/p/11808592.html

實驗

但是grep試了半天,沒找到能輸出分組的辦法,所以只能選擇使用sed
假設有個檔案a.txt

$ cat a.txt
xxxx ddd zzz fff
jdbc.url=jdbc:mysql://www.xxxx.com:3308/db_xxx?abcdefgh
jdbc.user=admin
jdbc.password=123456
nnn hhh

想要獲取host、port和db,我們可以寫成下面的指令碼

#!/bin/bash

host=`cat a.txt | grep "jdbc:mysql" | sed -r "s/.*:mysql:\/\/(.*):(.*)\/(.*)\?.*/\1/g"`
port=`cat a.txt | grep "jdbc:mysql" | sed -r "s/.*:mysql:\/\/(.*):(.*)\/(.*)\?.*/\2/g"`
dbname=`cat a.txt | grep "jdbc:mysql" | sed -r "s/.*:mysql:\/\/(.*):(.*)\/(.*)\?.*/\3/g"`

echo $host
echo $port
echo $dbname

結果:

$ sh help.sh 
www.xxxx.com
3308
db_xxx