Kevin Dorsey
Kevin Dorsey

Reputation: 1

Extracting output to use for a variable in bash

After running an fdisk -l, I want to be able to extract the volume group name to input later in a bash script. Example below:

fdisk -l | grep /dev/mapper/vg_palpatine
Disk /dev/mapper/vg_palpatine-lv_root: 105.1 GB
vgextend /dev/vg_$vg_name $partitioned_drive

I want to extract palpatine out of the fdisk -l output and input it as my $vg_name variable. I've been suggested a few different solutions, like sed, cut and awk, but I don't have much experience with those. How would I go about doing this?

Upvotes: 0

Views: 96

Answers (2)

m0skit0
m0skit0

Reputation: 25873

We can whole input string with the volume name only. To do this, we ask sed to replace (s///) regex matching with second expression:

vg_name=$(fdisk -l | grep /dev/mapper/vg_palpatine | sed -rn 's/.*vg_(.+)-lv_root.*/\1/p')

Regex explanation:

.* -> Any number of characters.

vg_(.+)-lv_root -> Capture the volume name as group 1.

We use the .* to match the whole input string, then we use group 1 (\1), which captures the volume name only, as substitution.

Note that if you want to use $vg_name on a different script you need to export it first.

Upvotes: 1

Farhad Farahi
Farhad Farahi

Reputation: 39277

You can use this:

vg_name=$(fdisk -l | grep /dev/mapper/vg_palpatine | sed -n "s/.*\/\(.*\)-.*/\1/p")
vgextend /dev/$vg_name $partitioned_drive

Upvotes: 0

Related Questions