0

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

1
  • So you want to remove anything starting with /bin/? Commented Mar 29, 2016 at 10:18

3 Answers 3

1
#! /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

Sign up to request clarification or add additional context in comments.

Comments

0

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 }.

Comments

0

If you are looking for an awk solution, one alternative is (similar in sed)

$ echo /usr/java/jdk1.8.0_77/jre/bin/java | 
  awk '{sub("/[^/]+/[^/]+$","")}1'

/usr/java/jdk1.8.0_77/jre

note that this is generic in the sense that it will chop down the last two levels in the path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.