regex - Bash 正则表达式——似乎无法匹配任何\s\S\d\D\w\W 等

标签 regex bash

我有一个脚本试图从 gparted 获取信息 block 。

我的数据看起来像:

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)

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

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

这适用于多行。

当我在 bash 脚本中对此进行测试时,我似乎无法匹配 \s\S -- 我做错了什么?

我正在通过如下脚本对此进行测试:

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

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

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

最佳答案

可能不支持\S 和\s,或者您不能将它们放在 [ ] 周围。尝试改用以下正则表达式:

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

编辑

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

#!/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.

关于regex - Bash 正则表达式——似乎无法匹配任何\s\S\d\D\w\W 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35799081/

相关文章:

regex - 将正则表达式转换为可在 Google 电子表格中使用的 re2?

linux - 我可以使用变量作为 AWK 的 {print} 的参数吗?

python - 在匹配组中用下划线替换空格字符?

arrays - 将 ColdFusion session 转换为数组(日期)正则表达式问题

bash - Github 操作 : Why an intermediate command failure in shell script would cause the whole step to fail?

Linux根据输入日期复制文件

linux - 斐波那契数列计算器

bash - 对目录中的所有文件执行命令

python - Perl 中 $1 的 Python 等价物是什么,或者正则表达式中的任何其他特殊变量?

regex - 引号之间匹配的正则表达式,包含转义引号