简体   繁体   中英

How to extract full paths from grep output using regular expression

I need to automatically detect any USB drives plugged in, mounted or not, mount the ones not mounted already in folders that have the name of the given name of the device (like it happens in a Windows machine by default) and get the routes of the mount points of all the devices. The devices should be mounted in folders in /media/pi (using a Raspberry Pi, so pi is my username). This is what I'm doing:

To get the path of all mounter devices:

1) Run lsblk , outputs:

NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda           8:0    1 14.4G  0 disk 
└─sda1        8:1    1 14.4G  0 part /media/pi/D0B46928B4691270
sdb           8:16   1 14.3G  0 disk 
└─sdb1        8:17   1 14.3G  0 part /media/pi/MI PENDRIVE
mmcblk0     179:0    0 14.9G  0 disk 
├─mmcblk0p1 179:1    0 41.8M  0 part /boot
└─mmcblk0p2 179:2    0 14.8G  0 part /

2) With a particularly crafted line, I can filter out some unnecessary info:

I run lsblk | grep 'sd' | grep 'media' lsblk | grep 'sd' | grep 'media' lsblk | grep 'sd' | grep 'media' which outputs:

└─sda1        8:1    1 14.4G  0 part /media/pi/D0B46928B4691270
└─sdb1        8:17   1 14.3G  0 part /media/pi/MI PENDRIVE

I need to get /media/pi/D0B46928B4691270 and /media/pi/MI PENDRIVE , preferably in an array. Currently I'm doing this:

lsblk | grep 'sd' | grep 'media' | cut -d '/' -f 4

But it only works with paths that have no spaces and the output of grep is not an array of course. What would be a clean way of doing this with regular expressions?

Thanks.

lsblk supports json output with the -J flag. I would recommend that if you want to parse the output:

lsblk -J | jq '..|.?|select(.name|startswith("sd")).mountpoint // empty'

Something like this?

$ echo "$f"
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda           8:0    1 14.4G  0 disk 
└─sda1        8:1    1 14.4G  0 part /media/pi/D0B46928B4691270
sdb           8:16   1 14.3G  0 disk 
└─sdb1        8:17   1 14.3G  0 part /media/pi/MI PENDRIVE
mmcblk0     179:0    0 14.9G  0 disk 
├─mmcblk0p1 179:1    0 41.8M  0 part /boot
└─mmcblk0p2 179:2    0 14.8G  0 part /

$ grep -o '/media/.*$' <<<"$f"
/media/pi/D0B46928B4691270
/media/pi/MI PENDRIVE

$ IFS=$'\n' drives=( $(grep -o '/media/.*$' <<<"$f") )

$ printf '%s\n' "${drives[@]}"
/media/pi/D0B46928B4691270
/media/pi/MI PENDRIVE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM