This post doesn’t show you how to do anything very useful, unless you are as bad at remembering device names as I am, but I thought it worth posting because of the way it solves the problem, which I quite like.
There have been a few times recently when I’ve wanted to know what mass storage devices there are on a linux system. This is easy enough to figure out by using ‘find’ to return all the paths containing ‘stat’ in ‘/sys’.
(And yes, like a lot of modern machines mine does have an awful lot of storage devices – and the first three don’t actually exist!)
Great, this command does just what I wanted, except that I what I needed was to be able to enumerate each device name in a script. Simple I thought, the device names are the penultimate field in each file path, I’ll just use ‘cut’ to extract the second field from the right and I’m sorted….
Unfortunately though that sounds like a good idea it wont work, as ‘cut’ can only count delimiters from the left and trying to use a negative value to count from the right doesn’t work!
So if ‘cut’ can only count from the left the field I wanted was going to have to be the second field in the string, but how?
The answer lies in the fact that when finding the field we don’t care how readable the string is, we just need the delimiters to be in the right place. If we reverse the order of all the letters in the string then the second field from the right becomes the second field from the left and we can extract it using ‘cut’, then in order to make the output readable, we just have to reverse it again.
In addition in the example below I’ve also used ‘sort’ to list the device names in order.
Now I don’t have any excuses for not being able to remember the device names of the partitions on my Raspberry Pi anymore!
Raspberry Pi is a trademark of the Raspberry Pi Foundation