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

18

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%%[-.]*}. Oct 7, 2012 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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