Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

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 at 20:19

3 Answers 3

$ 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
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 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 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 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 /. –  Stéphane Chazelas Jun 11 at 20:25

Bash

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

Your Answer

 
discard

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.