I'll start by saying that I think this problem is a little less innocent than it sounds.What I need to do: check for a folder within the PATH environment variable. It could be at the start or somewhere after. I just need to verify that that folder is there.Example of my problem - let's use /opt/gnome.SCENARIO 1: folder is not at the beginning of PATH# echo $PATH/sbin:/usr/sbin:/opt/gnome:/var/opt/gnome# echo $PATH | grep :/opt/gnome/sbin:/usr/sbin:/opt/gnome:/var/opt/gnomeNote that the grep needs to be specific enough so that it doesn't catch /var/opt/gnome. Hence the colon.SCENARIO 2: folder is at beginning of PATH.# echo $PATH/opt/gnome:/sbin:/usr/sbin:/var/opt/gnome# echo $PATH | grep ^/opt/gnome/opt/gnome:/sbin:/usr/sbin:/var/opt/gnomeThis is my problem - I need to search for either a colon or a start-of-line with this folder. What I would like to do is one of these two bracket expressions:# echo $PATH | grep [^:]/opt/gnome# echo $PATH | grep [:^]/opt/gnomeBUT [^ and [: have their own meanings. Therefore, the two commands above do not work.Is there a way I can grep for these two scenarios in one command?
Grep for pattern at start or middle of a line
shell script;text processing;path
If you're checking the content of the PATH environment variable, as opposed to looking for something in a file, then grep is the wrong tool. It's easier (and faster and arguably more readable) to do it in the shell.In bash, ksh and zsh:if [[ :$PATH: = *:/opt/gnome:* ]]; then : # already thereelse  PATH=$PATH:/opt/gnomefiPortably:case :$PATH: in  *:/opt/gnome:*) :;; # already there  *) PATH=$PATH:/opt/gnome;;esacNote the use of :$PATH: rather than $PATH; this way, the component is always surrounded by colons in the search string even if it was at the beginning or end of $PATH.If you're searching through a line of a file, then you can use the extended regexp (i.e. requiring grep -E) (^|:)/opt/gnome($|:) to match /opt/gnome but only if it's either at the beginning of a line or following a colon, and only if it's either at the end of the line or followed by a colon.