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.

Joaquin
  • 2,013
  • 3
  • 14
  • 26
elcharrua
  • 1,582
  • 6
  • 30
  • 50

2 Answers2

2

You want parameter expansion, not command substitution.

RESULT="${RESULT%/*}/"
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 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 Jul 17 '18 at 22:16
  • 1
    @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. – Charles Duffy Jul 17 '18 at 22:36
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...

dawg
  • 98,345
  • 23
  • 131
  • 206