regex 从字符串中提取绝对文件路径

0s7z1bwu  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(188)

我的示例文本是:

evince /media/ismail/SSDWorking/book-collection/_Books/kids/Coping Skills.pdf
/usr/lib/libreoffice/program/soffice.bin --impress file:///home/ismail/Desktop/LibreOffice%20Impress.odp --splash-pipe=5
/usr/bin/gjs /usr/bin/com.github.johnfactotum.Foliate /media/ismail/SSDWorking/book-collection/_Books/kids/Coping Skills.epub
mpv /media/ismail/8TBRaid0/_IslamNaseed/_JunaidJamshed/Mera Dil Badal De.mp3

这里我使用的两个正则表达式是:

grep -o '/media/ismail/.*'
grep -o 'file:\S*'

但是,我需要一个正则表达式来匹配两者,我不想使用像/media/ismail/这样的固定字符串,因为这可能会因机器而异。
为了清楚起见,首先,这些是Linux文件路径。其次,我期望的输出是:

/media/ismail/SSDWorking/book-collection/_Books/kids/Coping Skills.pdf
file:///home/ismail/Desktop/LibreOffice%20Impress.odp
/media/ismail/SSDWorking/book-collection/_Books/kids/Coping Skills.epub
/media/ismail/8TBRaid0/_IslamNaseed/_JunaidJamshed/Mera Dil Badal De.mp3
jvidinwx

jvidinwx1#

这个正则表达式匹配你想要的目标:

(file://)?(?<!\w)/(?!usr/).*?\.\S+

参见live demo
作为grep命令:

grep -oP '(file://)?(?<!\w)/(?!usr/).*?\.\S+'

参见live demo
-P选项用于 perl compatible regex

相关问题