Using awk
$ echo foo.mydomain.xyz | awk -F. '{print $1}'
foo
awk takes its input by "records" (which defaults to lines) and each record is divided into "fields." By default, fields are separated by white space. Here, we change the default so that the field separator is a period. For this example, that means that the first field is foo
, the second is mydomain
, and the third is xyz
. We tell awk to print only the first field, foo
.
To capture the short name to a shell variable:
shortname=$(hostname | awk -F. '{print $1}')
Using sed
This problem can also be solved with sed
:
$ echo foo.mydomain.xyz | sed 's/\..*//'
foo
Here, the substitution command, s/\..*//
, simply looks for a period and removes the period and all that follows.
Using shell
$ name=foo.mydomain.xyz
$ name=${name%%.*}
$ echo $name
foo
Can't believe I didn't know that. I should've looked at the man page. Thank you! – Mike – 2014-10-22T16:00:59.810