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?
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With