Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am new to bash, and I am creating a script that loops through the files in a directory and based on part of the filename, does something with the file, so far I have this:

#!/bin/bash
DIR="/Users/me/Documents/import/*"
for f in "$DIR"
do
  t=??????
  echo "Loading $f into $t..."
done

so $f will output something like this: /Users/me/Documents/import/time_dim-1272037430173 out of this, I want t to equal time_dim, the directory can be variable length and -1272037430173 is a fixed length (it's the unix timestamp btw).

What is the best way to go about this?

share|improve this question
up vote 3 down vote accepted

Untested:

t=`basename $f | sed -e 's/-[0-9]\+$//'`
share|improve this answer
    
it's close, it's returning time_dim-1272037429351 – Russ Bradberry Apr 23 '10 at 18:21
    
Try edited version above (+ changed to \+ in accordance with GNU sed regular expression documentation) – coneslayer Apr 23 '10 at 18:33
1  
still doesn't work, but i got this to: t=basename $f | sed 's/-[^-]*$//'`` – Russ Bradberry Apr 23 '10 at 18:35
    
the only problem i am having is that t is concatenating all of it before executing the echo, so I get something like: Loading /Users/me/Documents/import/* into date_dim demographic_dim event_log_facts ip_dim location_dim referal_dim time_dim rather than Loading /Users/me/Documents/import/time_dim-1272037430173 into time_dim... etc etc – Russ Bradberry Apr 23 '10 at 18:38
1  
Oh, I don't think you're actually looping over the files. Try removing the quotes around $DIR: for f in $DIR .... Personally, I would say DIR=/Users/me/Documents/import (so that $DIR is just a directory, as its name suggests) and then for f in $DIR/* but that's a matter of taste. – coneslayer Apr 23 '10 at 18:49

you could also do:

$ t=`basename $f|tr -d '[0-9-]'`
or

$ t=`basename $f|gawk -F- '{print $1;}'`

edited: i misread the question

share|improve this answer
What is the best way to go about this? 

the "best" way, using just bash internals, :)

$ s=/Users/me/Documents/import/time_dim-1272037430173
$  echo ${s%-*}
/Users/me/Documents/import/time_dim
$ t=${s%-*}
$ echo ${t##*/}
time_dim
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .