macosshellterminalsystem-profiler

Grep after grep - OSX Shell script


I am trying to find the name of my harddisk using OSX terminal using the system_profiler command. I'm sending the output to a text file. Here is part of the output...

Serial-ATA:

     Intel ICH8-M AHCI:

          Vendor: Intel
          Product: ICH8-M AHCI
          Link Speed: 1.5 Gigabit
          Negotiated Link Speed: 1.5 Gigabit
          Description: AHCI Version 1.10 Supported

            FUJITSU MHY2160BH:

              Capacity: 160.04 G

The part I am after is the FUJITSU MHY2160BH:, so I would like to grep the first line that starts with 16 spaces AFTER the Serial-ATA:. As the output of system_profiler has a variable number of lines, I don't really want to use grep -A.

I've tried all manner of greps, awks and seds but to no avail.

Any thoughts? Cheers.


Solution

  • This is much easier (and faster) to determine using diskutil than system_profiler:

    diskutil info /dev/disk0 | grep 'Media Name:' | cut -f2 -d:
    

    More Thoughts:

    system_profiler is expensive. You should generally only collect the data types you care about. For example:

    system_profiler SPSerialATADataType SPPrintersDataType
    

    Running a few smaller commands will generally be faster than running one giant system_profiler (~700k on my system) and then grepping it repeatedly (which requires re-reading the entire file several times). Running smaller commands can avoid the expensive data types entirely (like SPApplicationsDataType). The grep would be easier if you know you're only looking at SATA information.

    I'd still use diskutil to fetch this particular information, though. It's likely going to be much faster and easier (at least most of the time), and will let you get the correct drive. Both of these techniques are making an assumption about what drive you want. Your approach looks for the first SATA drive. My approach looks at disk0. The correct approach usually is to look at the boot drive (/). You can easily determine this using diskutil again:

    diskutil info `diskutil list / | head -1` | grep 'Media Name:' | cut -f2 -d: