7

Suppose I have a bash array

X=("a" "b c" "-d" "k j", "-f")

I want to filter by whether starting with "-" and get ("a" "b c" "k j") and ("-d" "-f") respectively.

How can I achieve that?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
Nan Hua
  • 3,414
  • 3
  • 17
  • 24
  • [Use `getopts`](http://stackoverflow.com/questions/16483119/example-of-how-to-use-getopts-in-bash) to parse arguments. – Amadan Apr 12 '16 at 23:51

2 Answers2

11

I think you'll have to iterate through the array:

$ X=("a" "b c" "-d" "k j", "-f")
$ for elem in "${X[@]}"; do [[ $elem == -* ]] && with+=("$elem") || without+=("$elem"); done
$ printf "%s\n" "${with[@]}"
-d
-f
$ printf "%s\n" "${without[@]}"
a
b c
k j,
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
4

From an answer to a similar question, you could do this:

A=$((IFS=$'\n' && echo "${X[*]}") | grep '^-')
B=$((IFS=$'\n' && echo "${X[*]}") | grep -v '^-')

From that answer:

The meat here is that IFS=$'\n' causes "${MY_ARR[*]}" to expand with newlines separating the items, so it can be piped through grep. In particular, this will handle spaces embedded inside the items of the array.

We then use grep / grep -v to filter in / out elements matching the pattern

3wordchant
  • 197
  • 1
  • 5