8

Say I have the following file names from an ls in a bash script:

things-hd-91-Statistics.db
things.things_domain_idx-hd-38-Data.db

In bash, how would it be able to get the first part of the string 'things' in either case? Basically remove the rest of the string past the first - or .

1 Answer 1

19

You would use parameter expansion:

string="things-hd-91-Statistics.db"
echo "${string%%-*}"
things

Where in ${parameter%%pattern} the 'pattern' (-*) is matched against the end of 'parameter'. The result is the expanded value of 'parameter' with the longest match deleted.

Similarly for your other example, the pattern would be %%.*

1
  • 2
    Or, combining the two in one: ${string%%[-.]*}. Commented Oct 7, 2012 at 6:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.