Inspected a character on a particular position in a word
I have a variable in my shell script, say $DEVICE, which contains the following string:
Code:
/dev/scd0 Code:
"0" in /dev/scd0 Now I would like to inspect which letter is there after the string /dev/scd? So for example what is there at the position "*" in the string /dev/scd* Thanks |
echo $DEVICE | sed 's-^/dev/scd--'
will strip all but the trailing device number. Assign that to a variable: DEVNO=$(echo $DEVICE | sed 's-^/dev/scd--') You can also use shell variable string manipulation as well, but the above is easier perhaps for you to initially understand. |
dev=/dev/scd2
echo $dev|cut -c9 2 |
Or perhaps better yet:
Code:
echo /dev/scd26 | perl -lne 'print $1 if /(\d+)$/' |
I think in this case shell variable string manipulation is pretty clear (assuming bash):
Code:
~/tmp$ echo $DEVICE |
The problem I personally have with parameter expansion for variables is that it is generally limited and certainly non-intuitive for new users. And once you need slightly more complex patterns, it becomes unwieldy. It uses only a limited form of filename patterns, and doesn't behave as one might expect:
Code:
$ DISK=/dev/sda22 |
Code:
echo $DEVICE |
... but I think one shouldn't have to think hard, worrying about searching the code for finding various oddities like :8:4, which are very specific to only certain devices types. For example, the solution offered doesn't work for devices with varying pattern lengths. Assume we want to find the unit number for either raidNN or sdaNN:
Code:
$ DISK=/dev/raid20 |
Two more methods:
To return only the part of the line which matches the search pattern:- Code:
echo /dev/raid20 | grep -o '[0-9]*$' Code:
echo /dev/raid20 | tr -d '[:alpha:][:punct:]' |
Who says computer people are not creative!? :-)
Good stuff all. |
Code:
# DEVICE=/dev/scd1 |
All times are GMT -5. The time now is 07:42 AM. |