Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash split string

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?

like image 705
idobr Avatar asked Jan 31 '13 15:01

idobr


People also ask

How do I split a string in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.


1 Answers

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.
like image 141
fedorqui 'SO stop harming' Avatar answered Nov 04 '22 00:11

fedorqui 'SO stop harming'