Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract Absolute File Path From a String

My sample text is:

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

Here the two regex I am using are:

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

However, I need a regex that will match both and I do not want to use fixed string like /media/ismail/ as this might vary from machine to machine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To be clear, first of all, these are Linux file paths. Secondly, my expected output is:

/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

>Solution :

This regex matches your desired targets:

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

See live demo.

As a grep command:

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

See live demo.

The -P option is for perl compatible regex

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading