0

I have a scenario where I am creating a new variable that will have only the servces values from a list of values available in filex.

$ cat filex

all_name1_db
all_name2_dm
alm_service1_ax
all_name3_du
alz_name4_dx
ali_name5_dk
alk_service2_av
alf_name6_df
alj_name7_dq

Here is the code that I use to create a variable services which will have only the values that has services in it.

for x in $filex
do
 if [[ $x == *"service1"* ]] || [[ $x == *"service2"* ]];then
   Services+=$x","
 fi
done

My end result will be a comma delimited value shown below.

$ cat $Services

alm_service1_ax,alk_service2_av

The problem now is, the service value is keep on increasing in filex and I can't extend my if statement by adding ||. For instance, if I have a new service say bum_service3_bk included in filex then my if statement would look like this..

...
 if [[ $x == *"service1"* ]] || [[ $x == *"service2"* ]] || [[ $x == *"service3"* ]] ;then
...

and this will keep on increasing for every new service added in filex

Is there a way to write an if statement to have a single condition that can accommodate multiple or conditions or any better way to tackle my issue?

1
  • What's the problem with adding more || parts? Can you not simply do [[ $x = *service* ]] here? If you want something shorter, you can use a standard case construct instead of those ksh [[...]]s: case $x in service1|service2|service3) ...;; esac Commented Sep 30, 2016 at 7:56

2 Answers 2

0

Avoid loops to process text. Here:

grep 'service[123]' filex | paste -sd , -

Or:

grep 'service1
service2
service3' filex | paste -sd , -
1
  • 1
    What if I need to write the else part to another variable? In this case, I want to write the name values to another varible Nmaes. Using if statement I can achieve this using else. How can we go about that? Commented Sep 30, 2016 at 7:44
0

If you need one line answer then use :

grep "service" filex | xargs echo | sed 's/ /, /g'

OR

if you need conditional syntax then you can do like :

while read -r line
do
if [[ $line == *"service"* ]]
then
   Services+=("$line")
fi
done < "/tmp/filex"

echo "${Services[@]}" | tr ' ' ,

It will gives like:

alm_service1_ax,alk_service2_av,alk_service5_av,alk_service3_aff,alk_service5_afds

/tmp/filex - is path of your file

echo "${Services[@]}" | tr ' ' , - printing comma separated array

1
  • I have provided the service name as generic. The actual service name is different country's name. Like, Japan, US, China. I want to build the service string with the services that has the above country names. The way I use is multiple or conditions in the if statement. Is it possible to make a config file and maintain all the country names in it and do a lookup from it? Commented Oct 3, 2016 at 10:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .