我有一个脚本试图从 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/