I have following string in my shell script. /usr/java/jdk1.8.0_77/jre/bin/java What is the best way to split it into /usr/java/jdk1.8.0_77/jre
3 Answers
#! /bin/sh
path=/usr/java/jdk1.8.0_77/jre/bin/java
short_path="${path%/bin*}"
echo $short_path
More string manipulation examples here: http://tldp.org/LDP/abs/html/string-manipulation.html
Comments
With awk, if you can setup the input and output separators correctly, the solution becomes intuitive:
echo /usr/java/jdk1.8.0_77/jre/bin/java | awk '{ NF -= 2 } 1' FS=/ OFS=/
Output:
/usr/java/jdk1.8.0_77/jre
Explanation
awk implicitly splits its input at the FS string (or pattern with some versions of awk). The number of fields is stored in the NF variable; subtracting two from NF results in leaving off the last two elements. The 1 at the end invokes the default code block: { print $0 }.
/bin/?