In a Bash shell script, I'm processing data that starts off like this:
string1-string2-string3-string4-etc
I need string1
and string2
assigned to unique variables, and string3-string4-etc
left together inside of another single unique variable. I played around with trying to set IFS but then string3
, string4
, and etc
were disconnected.
How can I get the data I want? I'd prefer builtin shell commands if possible, but gawk or other tools are fine too.
As long as the -
character is always a field separator and not embedded in any substrings, the following will work:
str='string1-string2-string3-string4-etc'
a=$(echo "$str" | cut -d- -f1)
b=$(echo "$str" | cut -d- -f2)
c=$(echo "$str" | cut -d- -f3-)
The cut utility does the work of using the dash as a delimiter to define the fields you want to capture, and Bash command substitution is used to assign the output from cut to a variable.
$ echo "$a"; echo "$b"; echo "$c"
string1
string2
string3-string4-etc
Use the built-in read
command:
str='string1-string2-string3-string4-etc'
IFS=- read str1 str2 the_rest <<< "$str"
Using Bash regex:
s=string1-string2-string3-string4-etc
pat="([^-]*)-([^-]*)-(.*)"
[[ $s =~ $pat ]]
echo "${BASH_REMATCH[1]}"
echo "${BASH_REMATCH[2]}"
echo "${BASH_REMATCH[3]}"
Output:
string1
string2
string3-string4-etc
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