Bash split string

idobr picture idobr · Jan 31, 2013 · Viewed 21.8k times · Source

I have the following data in array:

MY_ARR[0]="./path/path2/name.exe 'word1 word2' 'name1,name2'" 
MY_ARR[1]="./path/path2/name.exe 'word1 word2' 'name3,name4,name5'"
MY_ARR[2]=".name.exe 'word1 word2'"
MY_ARR[3]="name.exe"
MY_ARR[4]="./path/path2/name.exe 'word1 word2' 'name1'"
MY_ARR[5]="./path/path2/name.exe 'word1 word2' 'name.exe, name4.exe, name5.exe'"

I want to divide it into two variables: $file and $parameter.

Example:

file="./path/path2/name.exe"
parameter="'word1 word2' 'name1,name2'"

I can do it with awk:

parameter=$(echo "${MY_ARR[1]}" | awk -F\' '{print $2 $4}')
file=$(echo "${MY_ARR[1]}" | awk -F\' '{print $1}')

This needs to remove trailing spaces and looks to complicated.

Is there a better way to do it?

Answer

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · Jan 31, 2013

It looks like the separator between the fields is an space. Hence, you can use cut to split them:

file=$(echo "${MY_ARR[1]}" | cut -d' ' -f1)
parameter=$(echo "${MY_ARR[1]}" | cut -d' ' -f2-)
  • -f1 means the first parameter.
  • -f2- means everything from the second parameter.