tags:

views:

270

answers:

5

Using OS X, I need a one line bash script to look at a client mac hostname like: 12345-BA-PreSchool-LT.local

Where the first 5 digits are an asset serial number, and the hyphens separate a business unit code from a department name followed by something like 'LT' to denote a laptop.

I guess I need to echo the hostname and use a combination of sed, awk and perhaps cut to strip characters out to leave me with:
"BA PreSchool"

Any help much appreciated. This is what I have so far:

echo $HOSTNAME | sed 's/...\(...\)//' | sed 's/.local//'
+3  A: 
 echo "12345-BA-PreSchool-LT.local" | cut -d'-' -f2,3 | sed -e 's/-/ /g'

(Not on OSX, so not sure if cut is defined)

butterchicken
why not sed -e 'y/-/ /' or use tr?
William Pursell
Excellent, yes cut is defined and your line does work! Thanks.
Chris Hopkins
+3  A: 

I like to keep things simple :)

You could do it with just cut:

echo 12345-BA-PreSchool-LT.local | cut -d"-" -f2,3
BA-PreSchool

If you want to remove the hyphen you can use tr

echo 12345-BA-PreSchool-LT.local | cut -d"-" -f2,3 | tr "-" " "
BA PreSchool
Andre Miller
This works too! Thanks.
Chris Hopkins
+3  A: 

How about

echo $HOSTNAME ¦ awk 'BEGIN { FS = "-" } ; { print $2, $3 }'
Ralph Rickenbach
And also I confirm that this also works for me. Thanks for the help.
Chris Hopkins
A: 

Awk can solve your question easily.

echo "12345-BA-PreSchool-LT.local" | awk -F'-' '$0=$2" "$3'
BA PreSchool
Hirofumi Saito
A: 
bash$ string="12345-BA-PreSchool-LT.local"
bash$ IFS="-"
bash$ set -- $string
bash$ echo $2-$3
BA-PreSchool