4

I run a script with the param -A AA/BB . To get an array with AA and BB, i can do this.

INPUT_PARAM=(${AIRLINE_OPTION//-A / }) #get rid of the '-A ' in the begining
LIST=(${AIRLINES_PARAM//\// })         # split by '/'

Can we achieve this in a single line?

Thanks in advance.

2
  • 1
    You can also use ${AIRLINE_OPTION#-A } to remove -A from the beginning, which is shorter and portable. Commented Sep 27, 2013 at 14:09
  • Since one line is returning a modification of AIRLINE_OPTION, and the other is returning a modification of AIRLINES_PARAM, I suspect there's no way to do this in one command - they're two completely separate commands with separate inputs and separate outputs. Commented Sep 27, 2013 at 14:15

3 Answers 3

4

One way

IFS=/ read -r -a LIST <<< "${AIRLINE_OPTION//-A /}"

This places the output from the parameter substitution ${AIRLINE_OPTION//-A /} into a "here-string" and uses the bash read built-in to parse this into an array. Splitting by / is achieved by setting the value of IFS to / for the read command.

Sign up to request clarification or add additional context in comments.

Comments

2
LIST=( $(IFS=/; for x in ${AIRLINE_OPTION#-A }; do printf "$x "; done) )

This is a portable solution, but if your read supports -a and you don't mind portability then you should go for @1_CR's solution.

Comments

2

With awk, for example, you can create an array and store it in LIST variable:

$ LIST=($(awk -F"[\/ ]" '{print $2,$3}' <<< "-A AA/BB"))

Result:

$ echo ${LIST[0]}
AA
$ echo ${LIST[1]}
BB

Explanation

  • -F"[\/ ]" defines two possible field separators: a space or a slash /.
  • '{print $2$3}' prints the 2nd and 3rd fields based on those separators.

1 Comment

That looks better, now I can +1 :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.