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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this community$ 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
echo ${mysql_str}| cut -f 2 -d '/'
> expr ${mysql_str} : '/'${path_str}'/(.*)/' oracle/ext/ggs > echo $path_str home
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]'
echo
be happy with any number of arguments?
Jun 11, 2014 at 20:23
echo
. Try with string='* *'
for instance. Or with string=/home/oracle/ggs/text.ext
where IFS is /
.
Jun 11, 2014 at 20:25
Bash
IFS=/ read -ra a <<<'/home/oracle/ggs/text.ext' &&
(IFS=/; printf '%s\n' "${a[*]:2:2}")
oracle/ggs
echo oracle/ggs
will answer your question. Please clarify what the requirement are. Is that characters 7 to 16? From the 2nd to 4th/
?&%asdf$Chris$fdsa?#
for "the string between the$
" would clearly mean that the result isChris
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.