Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse/capture strings separated by dashes?

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.

like image 759
Gregg Avatar asked Mar 14 '16 03:03

Gregg


3 Answers

Use Cut and Command Substitution to Capture Fields

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.

Validation

$ echo "$a"; echo "$b"; echo "$c"
string1
string2
string3-string4-etc
like image 195
Todd A. Jacobs Avatar answered Nov 15 '22 19:11

Todd A. Jacobs


Use the built-in read command:

str='string1-string2-string3-string4-etc'
IFS=- read str1 str2 the_rest <<< "$str"
like image 22
chepner Avatar answered Nov 15 '22 18:11

chepner


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
like image 3
Jahid Avatar answered Nov 15 '22 17:11

Jahid