0

I have a list that looks like this:

['2    19   2839475239874 hda']

I need to extract the hda from the end. However, the hda may not always be the last chunk, hda may not always be only 3 letters (it could be 4 or 5, and it could include numbers); BUT it will always start with the letter 'h'.

After the hda is successfully extracted, I then need to insert that chunk into a dd command. That looks like this:

dd if=/dev/zero of=/dev/hda bs=512 count=1

But if the hda could be different each time I run the dd command, I need a way to have the 'hda' part of the dd command changeable.

Sorry if this is confusing, I am a beginner and confused myself! I've tried using startswith for extraction, but can't even get past there!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ohhiloveyouu
  • 101
  • 3
  • 8
  • `[' 2 19 2839475239874 hda']` a list with only one element? Why not just use a string, or there are more strings like this in the list? – zhangyangyu Jul 11 '13 at 12:22
  • @zhangyangyu No, this is the only list, and hda is the only string/chunk I need. Sorry if I didn't understand your questions properly. – ohhiloveyouu Jul 11 '13 at 12:30
  • @zhangyangyu, I think he just misstyped it. Read `['2','19','2839475239874','hda']` ;]. – Mathieu Marques Jul 11 '13 at 12:44

2 Answers2

1

Simply like so:

lst = ['2    19   2839475239874 hda']

# Extracting the device part
dev = filter(lambda s: s[0] is 'h', lst[0].split())[0]

# Inserting it
cmd = 'dd if=/dev/zero of=/dev/{0} bs=512 count=1'.format(dev)

You will want to check the case where you don't have any h-word in your list though.

Mathieu Marques
  • 1,678
  • 15
  • 33
1
>>> thelist = ['2    19   2839475239874 hda']
>>> [item for item in thelist[0].split() if item[0] == 'h'][0]
'hda'
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251