[techtalk] need help with a shell script

Laurel Fan lf25+ at andrew.cmu.edu
Tue Sep 26 16:52:19 EST 2000


Excerpts from linuxchix: 26-Sep-100 [techtalk] need help with a.. by
alissa bader at yahoo.com 
> with the "file" line reading like:
> [first-letter-of-domain]/db.[domain-minus-top-level-domain]

Here's a way to get the [domain-minus-top-level-domain] part:

   echo $DOMAIN | sed -e 's/\.[^\.]*$//'

This calls sed and tells it to execute the s/// command, basically,
s/something/somethingelse/ replaces "something" with "somethingelse".
The /'s are just used to separate the parts.

Here, I used a regular expression instead of just a string.  A regular
expression essentially does pattern matching.

So what my sed s/// command does is replace anything that matches the
regular expression \.[^\.]*$ with nothing.

Here's what the bits of \.[^\.]*$ mean:

\. means '.'. I had to use the \ to escape it, since . is special in
regexs (it means match anything)

[^\.] means anything except '.' (with the \ escaping . again)

* means "the thing before repeated any number, including 0, times",

$ means "at the end of the line"

So the the whole thing means:

replace:
  . then any number of things that aren't . at the end of the line
with:
  nothing

which should take off the last domain part.

To use this in your script, you can call it like:

  SUBDOMAIN = `echo $DOMAIN | sed -e 's/\.[^\.]*$//'`

(backticks (``) meaning "run this command and use the output")

---------
now for the [first-letter-of-domain] part:

  echo $DOMAIN | cut -c 1

the cut -c command outputs only the listed characters; cut -c 1
outputs only the 1st character.  It can also do fancier things, like
work on fields separated by delimiters, and there's an analogous paste
command.

so you could use:
  
  FIRST_LETTER = `echo $DOMAIN | cut -c 1`

----------

for the whole thing, you could get them in variables like above, and
then echo them like that, or you could stick it all one one line,
like:

echo `echo $DOMAIN | cut -c 1`/db.`echo $DOMAIN | sed -e 's/\.[^\.]*$//'`

(I haven't tried this stuff in a script, so if it doesn't work, tell
me and I'll actually try it)

If you want to learn more, read the manpages for sed, cut, and regex.
Regexs are a little hard to get the first time, though.






More information about the Techtalk mailing list