Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to get a string between two special characters. For example,


I want oracle/ggs in the above string.

How can I do this using bash?

share|improve this question
echo oracle/ggs will answer your question. Please clarify what the requirement are. Is that characters 7 to 16? From the 2nd to 4th /? – Stéphane Chazelas Jun 11 '14 at 20:19
@StéphaneChazelas I was just as confused as you were...Well, for a starter: when I want a string between two special characters I usually assume that there will be no special character of the same kind in between! So to say, parsing the (silly) string &%asdf$Chris$fdsa?# for "the string between the $" would clearly mean that the result is Chris and, as visible, there is no other $ sign in between. How else could the parser decide?? -- This question ought to be flagged as "too specific" as the technique described in the answers may not be needed elsewhere but in this lone case. – syntaxerror Feb 8 at 0:11
$ expr /home/oracle/ggs/text.ext : '/home/\(.*\)/'

That returns the part after /home/ and before the last /.

Other possible approaches that will fulfil your requirements:

$ echo /home/oracle/ggs/text.ext | cut -d/ -f3,4
$ echo /home/oracle/ggs/text.ext | cut -c 7-16
$ echo oracle/ggs
share|improve this answer
I got what I need thanks. >mysql_str=/home/oracle/ext/ggs/text.ext > path_str=echo ${mysql_str}| cut -f 2 -d '/' > expr ${mysql_str} : '/'${path_str}'/(.*)/' oracle/ext/ggs > echo $path_str home – BOB Jun 11 '14 at 20:38

For this particular example, you can use awk:

echo "$string" | awk -F '/' '{printf "%s%s%s\n" ,$2,FS,$3}'

The same in Perl:

echo "$string" | perl -lanF '/' -E '$,="/";say @F[1,2]'
share|improve this answer
oracle@ipt:> echo $x | awk -F '/' '{printf "%s%s%s\n" ,$3,FS,$4}' oracle/ggs I want to get the $4 dynamically any suggestions please? – BOB Jun 11 '14 at 20:09
@StéphaneChazelas Can you please explain why the quotes are needed here? Won't echo be happy with any number of arguments? – Joseph R. Jun 11 '14 at 20:23
Leaving a variable unquoted in list context is the split+glob operator (the variable is split into words and each word is subject to globbing), that's independent of echo. Try with string='* *' for instance. Or with string=/home/oracle/ggs/text.ext where IFS is /. – Stéphane Chazelas Jun 11 '14 at 20:25


IFS=/ read -ra a <<<'/home/oracle/ggs/text.ext' && 
(IFS=/; printf '%s\n' "${a[*]:2:2}") 
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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