1

The parameter list include the following example values

# echo $list
master01.montil131.com worker01.montil131.com worker02.montil131.com

In order to find the word that include master string I do the following

list=$( for i in ` echo  $list `; do [[ $i =~ master ]] && echo $i ; done )

echo $list
master01.montil131.com

but this approach to find the string with master word isn't elegant way

Any other suggestion how to find specific word in list ?

  • is $list a variable that contains the string "master01.montil131.com worker01.montil131.com worker02.montil131.com" ? a space separated list of words stored in a variable? – glenn jackman Feb 19 at 15:16
  • just one space between words ( no other comma separator )' – yael Feb 19 at 15:17
  • Unrelated: Why do you store a list in a string? It would be better to have it in an array... – Kusalananda Feb 19 at 20:55
1

Why not use simple grep command, I am assuming there are no spaces in a word in the list.

 echo $list | tr ' ' '\n' | grep master

It will replace space with new line and will then grep word master.

2

Use grep -o:

grep -o "[^ ]*master[^ ]*" <<<"$list"

If you know that you always have just master* and worker*, you can use Shell methods:

echo "${list// *worker[^ ]*/}"
1
grep -ow 'master[^ ]*' <<<"$list"

or, with GNU grep,

grep -Pow 'master\S+' <<<"$list"

The -o would extract the matching bit of the string in $list, and -w would ensure that we don't match themaster or some other word that does not start with master.

The \S in the second command is a PCRE that will match any non-space character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.