Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Bash script to check if a string is present in a comma separated list of strings

Tags:

bash

shell

I would like to know a neat way in which I can check to see if a string is there in a comma separated value of strings. eg: if

x="abc,def,ghi"
y="abc"

it should return true

and if

y="ab"

then it should return false

like image 528
Nikhil Titus Avatar asked Mar 27 '15 12:03

Nikhil Titus


2 Answers

You could use globs:

[[ ",$x," = *",$y,"* ]]
like image 56
PSkocik Avatar answered Sep 20 '22 07:09

PSkocik


Use bash's regular-expression-matching operator, =~:

[[ $x =~ (^|,)"$y"(,|$) ]]

Caveat: While the above regex happens to be portable, the particular flavor of regular expressions supported by =~ is platform-dependent due to use of a given platform's regex libraries.

Case in point: hek2mgl suggests use of \b to match word boundaries, which works on Linux, but not OSX, for instance. The closest thing to \b in POSIX are [[:<:]] and [[:>:]], but, unfortunately, these don't work on Linux.

like image 42
mklement0 Avatar answered Sep 17 '22 07:09

mklement0