1

I'm working on a script which checks if file exists. If it exists then I want to get the route.

What I did is the following:

RESULT_=$(find $PWD -name someRandom.json)

This returns the path to the file:

/Users/guest/workspace/random_repo/random/some_folder/someRandom.json

I'm stuck in the way to navigate among files. Is there a way of replacing someRandom.json with '' so I can do:

cd /Users/guest/workspace/random_repo/random/some_folder/

I tried using the solution provided here but it isn't working. I tried the following:

RESULT=$($RESULT/someRandom.json/'')
echo $RESULT

And this returns no such file or directory.

1
  • Every character counts. Commented Jul 17, 2018 at 22:06

2 Answers 2

2

given:

$ echo "$result"
/Users/guest/workspace/random_repo/random/some_folder/someRandom.json

You can get the file name:

$ basename "$result"
someRandom.json

Or the path:

$ dirname "$result"
/Users/guest/workspace/random_repo/random/some_folder

Or you can use substring deletion:

$ echo "${result%/*}"
/Users/guest/workspace/random_repo/random/some_folder

Or, given the file name and the full path, just remove the file name:

$ echo "$tgt"
someRandom.json
$ echo "${result%"$tgt"}"
/Users/guest/workspace/random_repo/random/some_folder/

There are many examples of Bash string manipulation:

BashFAQ/100

BashFAQ/073

Bash Hacker's Parameter Expansion

Side note: Avoid using CAPITAL_NAMES for Bash variables. They are reserved for Bash use by convention...

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

Comments

2

You want parameter expansion, not command substitution.

RESULT="${RESULT%/*}/"

2 Comments

You can just use exec in the find command. 'find $PWD -name someRandom.json -exec dirname {} \;' And to cd to it: cd $(find $PWD -name someRandom.json -exec dirname {} \;)
@Jebby, that's going to behave badly if the directory names have spaces. "$PWD" should be quoted, -quit should be added at the very end of the find command (so it can't return more than one directory), and the command substitution as a whole should have quotes around it.

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.