Alex Rivera | Logout

Split 1 argument into 2 arguments using regexp in a bash script

Asked 2012-07-10T14:58:08.307
9

Here's my situation. Currently, I have a script that accepts two arguments: book name and chapter name. For example:

$ myscript book1 chap1

Now, for reasons that would take a long time to explain, I would prefer my script to be able to take a single argument of the following format: {book name}.{chapter name}. For example:

$ myscript book1.chap1

The difficulty for me is that I do not know how to take a string $1=abc.xyz and turn it into two separate variables, $var1=abc and $var2=xyz. How can I do this?

Edit
Report

2 Answers

0

You can use parentheses to capture the two parts; afterwards, you can use backreferences to grab them again. The syntax differs between languages; check http://www.regular-expressions.info/brackets.html for a lesson on backreferences in general.

answered 2012-07-10T15:00:32.683
0

Pattern Subsitution with Shell Parameter Expansion

There are a lot of ways to accomplish what you're trying to do. One of the ways not covered in other answers is pattern substitution.

If you know that the value will always split correctly on a period, you can apply pattern substitution to the value so that it will be easy to tokenize with IFS. For example:

set -- foo.bar
myvar="${1/./ }"
echo $myvar

This will yield foo bar.

answered 2012-07-10T15:27:48.950

Your Answer