Bash 正则表达式——似乎无法匹配任何 s S d D w W 等 [英] Bash Regular Expression -- Can't seem to match any of s S d D w W etc

查看:31
本文介绍了Bash 正则表达式——似乎无法匹配任何 s S d D w W 等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本试图从 gparted 获取信息块.

I have a script that is trying to get blocks of information from gparted.

我的数据看起来像:

Disk /dev/sda: 42.9GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system     Flags
 1      1049kB  316MB   315MB   primary  ext4            boot
 2      316MB   38.7GB  38.4GB  primary  ext4
 3      38.7GB  42.9GB  4228MB  primary  linux-swap(v1)

log4net.xml
Model: VMware Virtual disk (scsi)
Disk /dev/sdb: 42.9GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system     Flags
 1      1049kB  316MB   315MB   primary  ext4            boot
 5      316MB   38.7GB  38.4GB  primary  ext4
 6      38.7GB  42.9GB  4228MB  primary  linux-swap(v1)

我使用正则表达式将其分成两个磁盘块

I use a regex to break this into two Disk blocks

^Disk (/dev[S]+):((?!Disk)[sS])*

这适用于多行.

当我在 bash 脚本中测试时,我似乎无法匹配 sS -- 我做错了什么?

When I test this in a bash script, I can't seem to match s, or S -- What am I doing wrong?

我正在通过一个脚本来测试这个:

I am testing this through a script like:

data=`cat disks.txt`
morematches=1
x=0
regex="^Disk (/dev[S]+):((?!Disk)[sS])*"

if [[ $data =~ $regex ]]; then
echo "Matched"
while [ $morematches == 1 ]
do
        x=$[x+1]
        if [[ ${BASH_REMATCH[x]} != "" ]]; then
                echo $x "matched" ${BASH_REMATCH[x]}
        else
                echo $x "Did not match"
                morematches=0;
        fi

done

fi

但是,当我遍历正则表达式的测试部分时,每当我匹配 sS 时,它都不起作用——我在做什么错了吗?

However, when I walk through testing parts of the regex, Whenever I match a s or S, it doesn't work -- what am I doing wrong?

推荐答案

也许不支持 S 和 s,或者您不能将它们放在 [ ] 周围.尝试使用以下正则表达式:

Perhaps S and s are not supported, or that you cannot place them around [ ]. Try to use the following regex instead:

^Disk[[:space:]]+/dev[^[:space:]]+:[[:space:]]+[^[:space:]]+

编辑

您似乎确实想要获取匹配的字段.为此,我将脚本简化为这个.

It seems like you actually want to get the matching fields. I simplified the script to this for that.

#!/bin/bash 

regex='^Disk[[:space:]]+(/dev[^[:space:]]+):[[:space:]]+(.*)'

while read line; do
    [[ $line =~ $regex ]] && echo "${BASH_REMATCH[1]} matches ${BASH_REMATCH[2]}."
done < disks.txt

产生:

/dev/sda matches 42.9GB.
/dev/sdb matches 42.9GB.

这篇关于Bash 正则表达式——似乎无法匹配任何 s S d D w W 等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆