Alex Ritchie
Alex Ritchie

Reputation: 339

Split a string on a word in Bash

I wish to be able to split a string on a word. Essentially a multi-character delimiter. For example, I have a string:

test-server-domain-name.com

I wish to keep everything before 'domain' so the output would be:

test-server-

Note: I cannot cut on the '-'. I have to be able to cut before the term 'domain' as the string's format will vary but 'domain' will always be present and I will always want to capture the elements before 'domain'.

Is this possible in bash?

Upvotes: 5

Views: 9585

Answers (3)

user3633056
user3633056

Reputation: 1

Incrivel is correct.

$ name=test-server-domain-name.com
$ echo $name                                  
test-server-domain-name.com
$ echo $name |awk -F '-domain-name.com' '{print $1}'
test-server                              

Upvotes: 0

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

This will cut at the first domain it finds:

cutat=domain
fqdm=test-server-domain-name.com

res=${fqdm%%${cutat}*}
echo $res

Output:

test-server-

If you have multiple domains in the string and want to cut on the last, use res=${fqdm%${cutat}*} (one %) instead.


From Shell Parameter Expansion:

${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Upvotes: 6

Incrivel Monstro Verde
Incrivel Monstro Verde

Reputation: 948

Use awk:

echo test-server-domain-name.com | awk -F 'domain' '{print $1}'

Upvotes: 9

Related Questions