How can I print everything before a match?

1

After I run hostname I get the FQDN like so:

$ hostname
foo.mydomain.xyz

I'd like to only get the short name foo so I can store it as a variable in a script. I've tried some ways with awk by matching . (the dot) but haven't had much luck.

Mike

Posted 2014-10-22T00:53:22.567

Reputation: 11

Answers

1

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

John1024

Posted 2014-10-22T00:53:22.567

Reputation: 13 893

1

It's not necessary to use sed, awk, grep. Just use the -s flag of hostname:

$ hostname -s
foo

From the man page:

  -s, --short
        Display the short host name. This is the host name cut at the first dot.

chaos

Posted 2014-10-22T00:53:22.567

Reputation: 3 704

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