3

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

/home/oracle/ggs/text.ext

I want oracle/ggs in the above string.

How can I do this using bash?

2
  • echo oracle/ggs will answer your question. Please clarify what the requirement are. Is that characters 7 to 16? From the 2nd to 4th /? Jun 11, 2014 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. Feb 8, 2016 at 0:11

3 Answers 3

4
$ expr /home/oracle/ggs/text.ext : '/home/\(.*\)/'
oracle/ggs

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
oracle/ggs
$ echo /home/oracle/ggs/text.ext | cut -c 7-16
oracle/ggs
$ echo oracle/ggs
oracle/ggs
1
  • 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, 2014 at 20:38
3

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]'
3
  • 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, 2014 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, 2014 at 20:23
  • 1
    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 /. Jun 11, 2014 at 20:25
0

Bash

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

You must log in to answer this question.

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