4

I am trying to determine the Startsector of a .img file from within a bash script so it can be correctly mounted from within the script. I have been using the file command to easily find the Startsector - how ever I'm not sure how to extract that number from the output. I think the answer lies with using awk but I cannot for the life of me fathom out how to do it.

Here is the output of the file command for reference:

kemra102@kaon:~/Downloads$ file 2012-07-15-wheezy-raspbian.img
2012-07-15-wheezy-raspbian.img: x86 boot sector; partition 1: ID=0xc, starthead 130, startsector 8192, 114688 sectors; partition 2: ID=0x83, starthead 165, startsector 122880, 3665920 sectors, code offset 0xb8
kemra102@kaon:~/Downloads$ 

2 Answers 2

2

It's a bit easier with sed or perl than with awk. With sed: match the whole line, looking for partition 1 followed by startsector 1234 (or any other sequence of digits) with no ; in between. Replace that whole line by just the digit, and print the result. You can change partition 1 to partition 2, of course.

sed -n 's/^.*partition 1:[^;]* startsector \([0-9][0-9]*\).*$/\1/p'

With perl: look for a substring consisting of partition 1 followed by startsector 1234 with no ; in between; save the digits after startsector in a group. If there's a match, print the digits.

perl -l -ne '/partition 1:[^;]* startsector ([0-9]+)/ and print $1'
0
2
file 2012-07-15-wheezy-raspdian.img     | \
    grep -oP '(?<=startsector )[0-9]+'  | \
    sed -n '1p'

If you change 1 to any other number in sed -n '1p' it will give you the other occurrences.

4
  • 2
    file 2012-07-15-wheezy-raspbian.img | grep -oP '(?<=startsector )[0-9]+' (piping the output from the original command to grep) would achieve the same thing.
    – reverendj1
    Aug 8, 2012 at 20:36
  • Good point. I misunderstood him and thought he was using another program to get the output he posted.
    – con-f-use
    Aug 8, 2012 at 20:43
  • Thanks both - it certainly does what I asked. One last thing though, how do I get it to show only the first out of the the results? I have tried the -m option but it always gives me 2 results even if I specify 1. My current thinking as this option doesn’t seem to be working is to pipe it through head afterwards.
    – kemra102
    Aug 8, 2012 at 20:45
  • See the edit of my answer.
    – con-f-use
    Aug 8, 2012 at 20:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .