Reputation: 371
I am currently working on a bash shell script and have a string that goes something like this:
"IP ADDRESS: 12313 isjdfisafjaslfsjfasd IP ADDRESS: 21311 asdfafa"
I am trying to break up the string into two arrays, one with the first half and the other with the second half. In this case, the ideal array will have two elements,
[IP ADDRESS: 12313 isjdfisafjaslfsjfasd] [IP ADDRESS: 21311 asdfafa]
Does anyone have any tips on how to do this? I have tried looking online but there weren't any questions too similar to this idea.
Upvotes: 0
Views: 78
Reputation: 22448
Using Bash Pattern Matching:
s="IP ADDRESS: 12313 isjdfisafjaslfsjfasd IP ADDRESS: 21311 asdfafa"
pat="(IP ADDRESS:.*)(IP ADDRESS:.*)"
[[ $s =~ $pat ]] && declare -a arr=("${BASH_REMATCH[@]:1:2}")
echo "First: ${arr[0]} Second: ${arr[1]}"
Output:
First: IP ADDRESS: 12313 isjdfisafjaslfsjfasd Second: IP ADDRESS: 21311 asdfafa
Upvotes: 0
Reputation: 84652
The simplest way is to use parameter expansion/substring extraction:
#!/bin/bash
c="IP ADDRESS: 12313 isjdfisafjaslfsjfasd IP ADDRESS: 21311 asdfafa"
a=( IP${c##* IP} ) # ${c##* IP} remove everything up to 'IP' from left
b=( ${c% IP*} ) # ${c% IP*} remove everything to first 'IP' from right
echo "a: ${a[@]}"
echo "b: ${b[@]}"
Output
$ splitscript.sh
a: IP ADDRESS: 21311 asdfafa
b: IP ADDRESS: 12313 isjdfisafjaslfsjfasd
Note: within parameter expansion braces (e.g. ${c##* IP}
) the space ' '
need not be escaped.
Upvotes: 3