-1

I am trying to automate the use of shred and putting the output into log files. Currently I am copying the serial number manually using

hdparm -I /dev/sd? | grep 'Serial\ Number'

I know that there is a way to have grep give me only the number and not the "Serial Number" text before it but I don't know how. Could someone how knows reg expressions help me?

1
5

Try awk instead of grep:

hdparm -I /dev/sd? | awk '/Serial Number/ { print $3 }'

or specify separator rather than accepting default of whitespace

hdparm -I /dev/sd? | awk -F':' '/Serial Number/ { print $2 }'
1
  • 1
    The second form has the disadvantage of leaving all the spaces between the colon and the serial number. Sep 2 '16 at 15:51
3

As that xkcd strip mentions perl, let's have a perl solution:

hdparm -I /dev/sd? | perl -nle '/Serial Number:\s+(.+)$/ && print $1'

A perl version of the awk solution in the other answer:

hdparm -I /dev/sd? | perl -anle '/Serial Number:/ && print $F[2]'
3

Try

hdparm -I /dev/sd? | grep -oP 'Serial Number:\s*\K.*'

This uses positive lookbehind to ignore pattern before our required string.. in this case Serial Number:\s*

1

sed?

hdparm -I /dev/sd? | sed -n 's/^.*Serial\ Number:  *\(.*\)$/\1/p'

(probably lots of other ways to do this using sed - this is just one way that I like: suppress the default print; match the required portion of the line; replace the entire line with it; then print it out.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.