return 0
return 0

Reputation: 4366

Parsing functionality in shell script

If I am trying to look up which host bus is the hard drive attached to, I would use

ls -ld /sys/block/sd*/device

it returns

lrwxrwxrwx 1 root root 0 Oct 18 14:52 /sys/block/sda/device -> ../../../1:0:0:0

Now if I want to parse out that "1" in the end of the above string, what would be the quickest way?

Sorry I am very new to shell scripting, I can't make full use of this powerful scripting language.

Thanks!

Upvotes: 0

Views: 50

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185025

Try doing this :

$ ls -ld /sys/block/sd*/device |  grep -oP '\d+(?=:\d+:\d:\d+)'
0
2
3

or

$ printf '%s\n' /sys/block/sd*/device |
    xargs readlink -f |
    grep -oP '\d+(?=:\d+:\d:\d+)'

and if you want only the first occurence :

grep ...-m1 ...

Upvotes: 1

Birei
Birei

Reputation: 36262

Split with slashes, select last field, split it with colons and select first result:

ls -ld /sys/block/sd*/device | awk -F'/' '{ split( $NF, arr, /:/ ); print arr[1] }'

It yields:

1

Upvotes: 2

Related Questions